//
// Fursin Program - Class CFPat for neural networks
//
#include <iostream.h>
#include <strstrea.h>  //In some versions must be strstream.h !!!
#include <stdlib.h>
#include <string.h>

#include "FPat.h"
#include "misc.h"

CFPat::CFPat(char xch0, char xch1)
{
	ch0=xch0;
	ch1=xch1;
	
	pPat=NULL;
	pFullNameOfPat=NULL;
}

CFPat::~CFPat(void)
{
	if (pFullNameOfPat!=NULL) delete pFullNameOfPat;
	if (pPat!=NULL) delete pPat;
}

//Loading Pattern
//Return:  0 - success
//        -1 - Can't open file
//        -2 - Unexpected end of file
//        -3 - Unknown character in pattern
int CFPat::Load(char *NameOfPat)
{
	ifstream inp;
	unsigned int ix1, iy1, ix, iy; 
	unsigned long i,il;
	char ch;

	pFullNameOfPat = new char[strlen(NameOfPat)+1];
	strcpy(pFullNameOfPat, NameOfPat);
	
	inp.open(pFullNameOfPat,ios::nocreate|ios::in);
	if (!inp) return -1;

	if (inp.eof()) 
	{
err_quit:
		inp.close();
		return -2;
	}

	inp >> ix1;
	
	if (inp.eof()) goto err_quit;
	inp >> iy1;

	Dx=ix1;
	Dy=iy1;

	il=ix1*iy1;	
	pPat = new char [il];

	i=0;
	for (iy=1; iy<=iy1; iy++)
	{
		for (ix=1; ix<=ix1; ix++)
		{
			if (inp.eof()) goto err_quit;
			inp >> ch;
			
			if (ch==ch0)      pPat[i]=0;
			else if (ch==ch1) pPat[i]=1;
			else return -3;
			
			i++;
		}
	}

	inp.close();
	
	return 0;
}

//Create pattern in RAM
int CFPat::Create(unsigned int x, unsigned int y)
{
	unsigned long i,il;	
	unsigned int ix, iy; 

	Dx=x;
	Dy=y;

	il=x*y;	
	pPat = new char [il];

	i=0;
	for (iy=1; iy<=y; iy++)
	{
		for (ix=1; ix<=x; ix++)
		{
			pPat[i]=0;
			i++;
		}
	}

	return 0;
}

//Saving pattern (and changing name if NameOfPat!="")
//Return:  0 - success
//        -1 - Can't open file
int CFPat::Save(char *NameOfPat)
{
	ofstream out;
	unsigned int q;
	unsigned int ix1, iy1, ix, iy; 
	unsigned long i,il;
	char ch;

	q=strlen(NameOfPat);
	if (q!=0)
	{
		pFullNameOfPat = new char[q+1];
		strcpy(pFullNameOfPat, NameOfPat);
	}
	
	out.open(pFullNameOfPat);
	if (!out) return -1;

	ix1=Dx;
	iy1=Dy;

	out << ix1 << '\n';
	out << iy1 << '\n';
	out << '\n';

	il=ix1*iy1;	

	i=0;
	for (iy=1; iy<=iy1; iy++)
	{
		for (ix=1; ix<=ix1; ix++)
		{
			if (pPat[i]==0) ch=ch0;
			else ch=ch1;
			
			out << ch;
			i++;
		}
		out << '\n';
	}

	out.close();

	return 0;
}
