/*
Adriane Boyd

Lexicon class.

*/

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

// Constructor
Lexicon::Lexicon()
{
	lexcount = 0;
}

// Destructor
Lexicon::~Lexicon()
{
}

// Reads the lexicon in from the given file
// Each line of the file should contain a word followed by whitespace followed
// by a terminal symbol
int Lexicon::read(ifstream& file)
{
	int i, j;
	char line[MAX_LINE_LEN];
	char name[MAX_NAME_LEN];
	char type[MAX_NAME_LEN];

	while(!file.eof() && lexcount < MAX_LEX)
	{
		strcpy(name, "");
		strcpy(type, "");

		file.getline(line, MAX_LINE_LEN);

		i = 0;

		while(isspace(line[i]))
		{
			i++;
		}
		j = 0;
		while(!isspace(line[i]) && line[i] != '\0')
		{
			name[j] = tolower(line[i]);
			i++;
			j++;
		}
		name[j] = '\0';
		while(isspace(line[i]))
		{
			i++;
		}
		j = 0;
		while(!isspace(line[i]) && line[i] != '\0')
		{
			type[j] = line[i];
			i++;
			j++;
		}
		type[j] = '\0';

		if(strcmp(name, "") != 0 && strcmp(type, "") != 0)
		{
			strncpy(lexicon[lexcount].name, name, MAX_NAME_LEN);
			strncpy(lexicon[lexcount].type, type, MAX_NAME_LEN);
			lexcount++;
		}
	}
}

// Returns the type associated with the word (should be a terminal symbol)
char *Lexicon::getType(char *word)
{
	int i;

	for(i = 0; i < lexcount; i++)
	{
		if(strcmp(lexicon[i].name, word) == 0)
		{
			return lexicon[i].type;
		}
	}

	return NULL;
}

// Prints the lexicon
void Lexicon::print()
{
	int i;

	cout << "Lexicon:" << endl;

	for(i = 0; i < lexcount; i++)
	{
		cout << i;
		cout << lexicon[i].name << " " << lexicon[i].type << endl;
	}
}
