#include "link-includes.h"
#include "assert.h"
#include "string.h"

int getConnectedWord(Linkage linkage, int word, char * connector);

int main() {

    Dictionary    dict;
    Parse_Options opts;
    Sentence      sent;
    Linkage       linkage;
    char *        diagram;
    char * 	  string;
    int           i, j, num_linkages, num_words, connectedWord;
    char *        input_string[] = {
       "This is a test of the constituent code in the API.",
       "The man has a gun."};

    opts  = parse_options_create();
    dict  = dictionary_create("4.0.dict", "4.0.knowledge", 
		    "4.0.constituent-knowledge", "4.0.affix");

    for (i=0; i<2; ++i) {
	sent = sentence_create(input_string[i], dict);
	num_linkages = sentence_parse(sent, opts);
	if (num_linkages > 0) {
	    linkage = linkage_create(0, sent, opts);
	    num_words = linkage_get_num_words(linkage);
	    assert(num_words >= 0);
	    for (j=0; j < num_words; ++j){
		    if( strcmp( sentence_get_word(sent, j), "has") == 0){
			    connectedWord = getConnectedWord(linkage, j, "Ss");
			    assert(connectedWord >= 0);
			    printf("%s aggregates ", 
				string = 
				  sentence_get_word(sent, connectedWord));
			    connectedWord = getConnectedWord(linkage, j, "Os");
			    assert(connectedWord >= 0);
			    printf("%s \n", 
				string = 
				  sentence_get_word(sent, connectedWord));
		    }
		    
	    }

	    linkage_delete(linkage);
	}
	sentence_delete(sent);
    }

    dictionary_delete(dict);
    parse_options_delete(opts);
    return 0;
}

int getConnectedWord(Linkage linkage, int word, char * connector){
	int i, numb_links;
	char * tempConnector;
	numb_links = linkage_get_num_links(linkage);
	assert(numb_links >= 0);
	for(i = 0;  i < numb_links; ++i) {
		if(linkage_get_link_lword(linkage, i) == word) {
			tempConnector 
				= linkage_get_link_label(linkage, i);
			if (strcmp (tempConnector, connector) == 0) {
				return linkage_get_link_rword(linkage, i);
			}
		}
		if(linkage_get_link_rword(linkage, i) == word) {
			tempConnector 
				= linkage_get_link_label(linkage, i);
			if (strcmp (tempConnector, connector) == 0) {
				return linkage_get_link_lword(linkage, i);
			}
		}
	}
	return -1;
}
