
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "fDictionary.h"

namespace fingers
{

	fDictionary::fDictionary()
	{

	}

	fDictionary::~fDictionary()
	{
		if ( loaded )
			unload();
	}

	bool fDictionary::load(const char* filename)
	{
		FILE* fp;

		fp = fopen(filename, "r");

		if ( !fp )
			return false;

		// OLD CODE! TRYING NEW ONE: MUCH BETTER APPROACH IN GENERAL

		/*fread(&count, sizeof(int), 1, fp);

		words = new fDictWord[count];

		int len;
		for ( int i = 0; i < count; i++ )
		{
			fread(&len, sizeof(int), 1, fp);

			words[i].word = new char[len+1];
			
			fread(words[i].word, sizeof(char), len, fp);

			words[i].word[len] = NULL;
		}*/

		char	buffer[MAX_WORD_LENGHT];
		char*	result;

		memset(buffer, 0, MAX_WORD_LENGHT);
		result = fgets(buffer, MAX_WORD_LENGHT, fp);

		count = atoi(result);

		if ( count > 0 )
		{
			int i	= 0;
			int len	= 0;

			words = new fDictWord[count];


			do
			{
				memset(buffer, 0, MAX_WORD_LENGHT);
				result = fgets(buffer, MAX_WORD_LENGHT, fp);

				if ( result )
				{
					if ( i > count )
						break;

					len = strlen(result);

					if ( buffer[len-1] == 10 )
					{
						buffer[len-1] = NULL;
						//len--;	// Something is fishy
					}
					else
						len++;		// what e fuck?

					words[i].word	= new char[len];

					memset(words[i].word, 0, len);
					memcpy(words[i].word, buffer, len);

					i++;
				}
			}
			while ( result );

			loaded = true;
		}
		else
		{
			return false;
		}

		return true;
	}

	void fDictionary::unload()
	{
		for ( int i = 0; i < count; i++ )
		{
			delete [] words[i].word;
		}

		delete [] words;
	}

	const char* fDictionary::getWord()
	{
		int number = count * (rand() / (RAND_MAX + 1.0f));

		return words[number].word;
	}

}