/*

Adriane Boyd

Main file.

*/

#include <fstream.h>
#include <string.h>
#include <ctype.h>
#include "tlist.h"
#include "grammar.h"
#include "lexicon.h"
#include "parser.h"

TList *readsent();

int main(int argc, char **argv)
{
	int success;
	char gfilename[MAX_NAME_LEN] = "", lfilename[MAX_NAME_LEN];

	ifstream ginfile, linfile;

	TList *sent;
	Grammar grammar;
	Lexicon lexicon;
	Parser parser;

	if(argc != 3)
	{
		cout << "Verwendung: parser grammatikdatei.txt lexikondatei.txt" << endl;
		exit(0);
	}

	strncpy(gfilename, argv[1], MAX_NAME_LEN);
	strncpy(lfilename, argv[2], MAX_NAME_LEN);

	ginfile.open(gfilename);

	if(ginfile.fail())
	{
		cout << "Couldn't open " << gfilename << endl;
		exit(1);
	}

	grammar.read(ginfile);

	linfile.open(lfilename);

	if(linfile.fail())
	{
		cout << "Couldn't open " << lfilename << endl;
		exit(1);
	}

	lexicon.read(linfile);

	cout << "PT-2 Parser" << endl;
	cout << "-----------" << endl;

	while(true)
	{
		sent = readsent();

		if(sent->count() == 0)
		{
			break;
		}

		success = parser.parse(sent, &grammar, &lexicon);

		if(!success)
		{
			cout << "\nSchlechter Satz" << endl;
		}
	}
}

// Read the sentence from standard input, converted all letters to lowercase and
// ignoring all punctuation
// Each word becomes an element of a TList
TList *readsent()
{
	TList *sent = new TList;

	int i, j;
	char line[MAX_LINE_LEN];
	char word[MAX_LINE_LEN];

	cout << "\nGeben Sie einen Satz ein (leeren Satz zum Verlassen):" << endl;

	cin.getline(line, MAX_LINE_LEN);

	i = 0;

	while(line[i] != '\0')
	{
		strcpy(word, "");

		while(!isalpha(line[i]) && line[i] != '\0')
		{
			i++;
		}

		j = 0;

		while(isalpha(line[i]) && line[i] != '\0')
		{
			word[j] = tolower(line[i]);
			i++;
			j++;
		}
		word[j] = '\0';

		if(strcmp(word, "") != 0)
		{
			sent->insertLast(word, 1);
		}
	}

	return sent;
}
