#include <string.h>
#include <iostream.h>
#include <fstream.h>

#include "FStatus.h"
#include "FNet.h"
#include "misc.h"

/////////////////////////// MAIN PROGRAM ///////////////////////////
int main(void)
{
	char ER[]="ERROR";

	const StrMaxLen=1024;
	
	char FTASK[]="learning.tsk";
	ifstream tsk;
	char StrBuf[StrMaxLen];
	int str1,str2;
	
	char NET[]="NET=";
	char ParamNET[StrMaxLen];

	char PATB[]="PAT_BEGIN=";
	char ParamPATB[StrMaxLen];

	char PATE[]="PAT_END=";
	char ParamPATE[StrMaxLen];

	char PATEXT[]=".pat";

	char PAT_PATH[]="PATS\\";
	char NET_PATH[]="NETS\\";

	int sts;

	CFStatus FStatus("learning.out");
	
	//program
	cout << "Fursin Program - 'Training of Hopfield Network'  (C)  V1.0\n";

	//reading file with task
	tsk.open(FTASK,ios::nocreate|ios::in);
	if (tsk==NULL)
	{
		FStatus.Set(ER,"Can't find file with task",true);
		return 1;
	}		

	//loop for sub-tasks
	do
	{
		// Getting first line -> "NET="
		str1=Rd(tsk, StrBuf, StrMaxLen);
		str2=GetParam(StrBuf, NET, ParamNET, StrMaxLen);
		if (str2!=0)
		{
err_quit:
			if (str2==-1) 
			{
				FStatus.Set(ER,"Empty line in file with task",true);
				return 1;
			}
			else if (str2==-2)
			{
				FStatus.Set(ER,"Line is too short in file with task",true);
				return 1;
			}
			else if (str2==-3)
			{
				FStatus.Set(ER,"Can't find reserved words in file with task",true);
				return 1;
			}
			return 1;
		}

		// Getting first line -> "PAT_BEGIN="
		str1=Rd(tsk, StrBuf, StrMaxLen);
		str2=GetParam(StrBuf, PATB, ParamPATB, StrMaxLen);
		if (str2!=0) goto err_quit;
		
		// Getting first line -> "PAT_END="
		str1=Rd(tsk, StrBuf, StrMaxLen);
		str2=GetParam(StrBuf, PATE, ParamPATE, StrMaxLen);
		if (str2!=0) goto err_quit;

		//Ready to start learning
		CFNet *pFNet = new CFNet(ParamNET, NET_PATH, StrMaxLen);

		//Learning
		sts=pFNet->Learn(ParamPATB, ParamPATE, PATEXT, PAT_PATH, true);
		delete pFNet;

		if (sts!=0)
		{
			if (sts==-1)
			{
				FStatus.Set(ER,"Length of PAT_BEGIN<>length of PAT_END",true);
				return 1;
			}
			else if (sts==-2)
			{
				FStatus.Set(ER,"PAT_BEGIN > PAT_END",true);
				return 1;
			}
			else if (sts==-3)
			{
				FStatus.Set(ER,"Dimensions of patterns for neural network are different",true);
				return 1;
			}
			else if (sts==-4)
			{
				FStatus.Set(ER,"Can't save neural network",true);
				return 1;
			}
			else if (sts==-11)
			{
				FStatus.Set(ER,"Can't open file with pattern",true);
				return 1;
			}
			else if (sts==-12)
			{
				FStatus.Set(ER,"Unexpected end of file with pattern",true);
				return 1;
			}
			else if (sts==-13)
			{
				FStatus.Set(ER,"Unknown character in pattern",true);
				return 1;
			}

			return 1;
		}

		//Read empty line or find EOF
		str1=Rd(tsk, StrBuf, StrMaxLen); 
	}
	while(str1>0);
		
	tsk.close();
	
	if (str1==-1)
	{
		FStatus.Set(ER,"String is too long in file with task",true);
		return 1;
	}
		
	FStatus.Set("OK","",false);

	return 0;
}
