/*File Name: cUniversNeib.cpp
  Author: Betti Oesterholz ; Date: 12.04.2005
  System: C++


  Copyright (C) 2004  Betti Oesterholz

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2, June 1991, of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

 This file contains tools for the univers.
*/
#include "cstring"

#ifdef linux
	#include "cKeyboard.h"//Linux Keyboard
#else
	#include <conio.h>//windows Keyboard
#endif

#include "cUniversNeib.h"


cUniversNeib::cUniversNeib( const char* parFN ):cUniversTools(),
	gridDist(0), gridPoints(0), gridAfterPoints(0), gridStartPoint(0.0),statisticFolderName(NULL),
	getDirect(0), directBaseName(NULL), directGridAll(NULL), bDirectParameterChanged(true), 
	getDist(0), distBaseName(NULL), distGridAll(NULL), bDistParameterChanged(true),
	getNeib(0), neibBaseName(NULL), neibGridAll(NULL), neibDist(0), bNeibParameterChanged(true),
	getPartSize(0), partSizeName(NULL), partSizeF(NULL), bPartSizeParameterChanged(true),
	timeOfLasteSave(time(0)), timeMaxBetweanSaves(0), timeOfIterationBegin(0),
	timeMaxTimeIteration(0), timeOfBegin(0), timeMaxTime(0)
/*this constructor constructs a new instanz of this objekt with the
parameter of the parameters in the parameterfile with the path parFN
pre: the name or path parFN of the parameterfile with the parameter to load
post: the instanze of this object with the parameter of the parameter file*/
{
setStatisticFolderName("./statistic/");
restoreParameter("Null_Parameter");
restoreParameter(parFN);
}

cUniversNeib::cUniversNeib(bool outC,unsigned long cutA,unsigned long mTm, unsigned long maxP, unsigned long cMP, const char* stat, const char* uFol, const char* bUN, double cutDim, double cutRatio,unsigned long gAP,unsigned long gD, unsigned long gP, double grSP, const char* statFoldN, unsigned long getDirc, const char* directBN, unsigned long getD, const char* distBN, unsigned long getN, unsigned int nGD, const char* neibBN, bool getPS, const char* partN):
	gridDist(0), gridPoints(0), gridAfterPoints(0), gridStartPoint(0.0),statisticFolderName(NULL),
	getDirect(0), directBaseName(NULL), directGridAll(NULL), bDirectParameterChanged(true), 
	getDist(0), distBaseName(NULL), distGridAll(NULL), bDistParameterChanged(true),
	getNeib(0), neibBaseName(NULL), neibGridAll(NULL), neibDist(0), bNeibParameterChanged(true),
	getPartSize(0), partSizeName(NULL), partSizeF(NULL), bPartSizeParameterChanged(true),
	timeOfLasteSave(time(0)), timeMaxBetweanSaves(0), timeOfIterationBegin(0),
	timeMaxTimeIteration(0), timeOfBegin(0), timeMaxTime(0)
/*parameter constructor, constructs a new univers with standart values
beware this constructor copies just the char* pointers, but not the string in them!
parameters: output comments outC,cut after cutA steps (cutA),number of maximal
ticks mTm, maximal number of Points maxP, name of the statistic file,
cutDim the dimension to prefer by cut cutNearDimension, cutRatio the Ratio
till wich to generate the max class by cut cutMaxClassRatio, gAP is the
number of points the univers should have before the grid is created,
gD is the distance the points in the initial (first) grid should have,
gP are the number of points the initial grid should have,
nGD is the distance till wich the number of neibours of the grid should be evalued,
every getDirc ticks the direct statistics are evalued and outputed,
every getD ticks is true the distance statistics are evalued and outputed,
every getN ticks is true the neibours statistics are evalued and outputed,
statFoldN is the name of the folder for distance and neibour statistics,
directBaseName(directBN), distBaseName(distBN),neibBaseName(neibBN),
	gridStartPoint(grSP),getPartSize(getPS)
if some every tick is 0 then the statistic is never evalued


in a tick all ponts of the univers are changed once
standart statistic file is: "./statistics.txt"
the grid is a list of points with wich the statistic data of the distances
and neibours are evalued
if the maximal number is reached, the actual tick is the last*/
{
setStatisticFolderName("./statistic/");
restoreParameter("Null_Parameter");
cUniversTools(outC,cutA,mTm,maxP, cMP, stat, uFol, bUN, cutDim ,cutRatio);
setGridDistance(gD); setNumberOfGridPoints(gP); setGridAfterPoints(gAP);
setGridStartPoint(grSP);
neibDist=nGD;
//set statistic files
getDirect=0; getDist=0; getNeib=0;//don't crate file when the statistic folder is seted
setStatisticFolderName(statFoldN);
getDirect=getDirc; getDist=getD; getNeib=getN;
setDirectBaseFileName(directBN); setDistanceBaseFileName(distBN); setNeibourBaseFileName(neibBN);
getPartSize=getPS;
setPartSizeFileName(partN);
}

cUniversNeib::cUniversNeib(cUniversNeib &uNeib):cUniversTools(uNeib), 
	gridDist(0), gridPoints(0), gridAfterPoints(0), gridStartPoint(0.0),statisticFolderName(NULL),
	getDirect(0), directBaseName(NULL), directGridAll(NULL), bDirectParameterChanged(true), 
	getDist(0), distBaseName(NULL), distGridAll(NULL), bDistParameterChanged(true),
	getNeib(0), neibBaseName(NULL), neibGridAll(NULL), neibDist(0), bNeibParameterChanged(true),
	getPartSize(0), partSizeName(NULL), partSizeF(NULL), bPartSizeParameterChanged(true),
	timeOfLasteSave(time(0)), timeMaxBetweanSaves(0), timeOfIterationBegin(0),
	timeMaxTimeIteration(0), timeOfBegin(0), timeMaxTime(0)
/*copy constructor, constructs a copy of the given univers uNeib;
file output cycles will be set to 0
pre: the univers uNeib to copy*/
{
//todo check

setGridDistance(uNeib.getGridDistance()); setNumberOfGridPoints(uNeib.getNumberOfGridPoints());
setGridAfterPoints(uNeib.getGridAfterPoints());
setGridStartPoint(uNeib.getGridStartPoint());
for (list<unsigned long>::iterator pItr=uNeib.gridN.begin();pItr!=uNeib.gridN.end();pItr++)
	{gridN.push_back(*pItr);}
getDirect=0; getDist=0; getNeib=0;getPartSize=0;
setStatisticFolderName(uNeib.getStatisticFolderName());
setDirectBaseFileName(uNeib.getDirectBaseFileName()); setDistanceBaseFileName(uNeib.getDistanceBaseFileName());
setNeibourBaseFileName(uNeib.getDistanceBaseFileName()); setPartSizeFileName(uNeib.getDistanceBaseFileName());
gridStartPoint=uNeib.gridStartPoint;
timeMaxBetweanSaves=uNeib.timeMaxBetweanSaves;
for (list<cParameter>::iterator pItr=uNeib.parameter.begin();pItr!=uNeib.parameter.end();pItr++)
	{parameter.push_back(*pItr);}
}

cUniversNeib::~cUniversNeib()
/*standart destructor
destructs the univers and closes all open files of the univers*/
{
delete [] statisticFolderName;delete [] directBaseName;
delete [] distBaseName;delete [] neibBaseName;delete [] partSizeName;
if (directGridAll!=NULL){directGridAll->close();delete directGridAll;}
if (partSizeF!=NULL){partSizeF->close();delete partSizeF;}
if (distGridAll!=NULL){distGridAll->close();delete distGridAll;}
if (neibGridAll!=NULL){neibGridAll->close();delete neibGridAll;}
if (parameterFile){delete [] parameterFile;}
}

bool cUniversNeib::setGridStartPoint(const double grSP)
/*set wher the grid start points in the univers should be,
if the grid is not created already, 0 the grid should begin with univers
first point, 1 grid should begin with univers last point
pre: the number wher grid start point in the univers should be
post: true if the wher grid start point in the univers should be is set
	to the value (when the grid is not created), else false*/
{
gridStartPoint=grSP;
if (gridStartPoint<0.0){gridStartPoint=0.0;}
if (gridStartPoint>1.0){gridStartPoint=1.0;}
return true;
}

bool cUniversNeib::setDirectStatistics(const unsigned long gDirc)
/*set how often the direct statistic schould be evalued and opens the all
direct file if it needs to
pre: after how much ticks the direct statistic should be evalued (if 0
	don't evalue)
post: true if the value is changed, else false*/
{
if (getDirect!=gDirc)
{
	bDirectParameterChanged=true;
	getDirect=gDirc;
	return true;
}
return false;
}

bool cUniversNeib::setGetPartSize(const unsigned long pSize)
/*set how often the maximal distance from the grid start point should be evalued
pre: after how much ticks the maximal distance from the grid start point
	should be evalued (if 0 don't evalue)
post: true if the value is changed, else false*/
{
if (getPartSize!=pSize)
{
	bPartSizeParameterChanged=true;
	getPartSize=pSize;
	return true;
}
return false;
}

bool cUniversNeib::setDistanceStatistics(const unsigned long gDist)
/*set how often the distance statistic schould be evalued and opens the all
dist file if it needs to (if 0 don't evalue)
pre: after how much ticks the distance statistic should be evalued (if 0
	don't evalue)
post: true if the value is changed, else false*/
{
if (getDist!=gDist)
{
	bDistParameterChanged=true;
	getDist=gDist;
	return true;
}
return false;
}

bool cUniversNeib::setNeibourStatistics(const unsigned long gNeib)
/*set how often the neibour statistic schould be evalued and opens the all
neib file if it needs to (if 0 don't evalue)
pre: after how much ticks the neibour statistic should be evalued (if 0
	don't evalue)
post: true if the value is changed, else false*/
{
if (getNeib!=gNeib)
{
	bNeibParameterChanged=true;
	getNeib=gNeib;
	return true;
}
return false;
}

bool cUniversNeib::setNeibourDistance(const unsigned long neibD)
/*set the distance till wich the neibours should be evalued
pre: the distance till wich the neibours should be evalued
post: true if the value is changed, else false*/
{
neibDist=neibD;
return true;
}

bool cUniversNeib::setStatisticFolderName( const char* statFN )
/*set the folder/path name in wich the statistics should be saved and
creats the new files for all statistics in theas directorys/paths
(beware old files are with the new name are overwriten)
post: the pointer to folder/path name in wich the statistics should be
	saved
post: true if the value is changed, else false*/
{
if (!statFN)
{//if no string is given, don't change
	return false;
}
if (statisticFolderName) 
{//realy new name
	if ( strcmp(statisticFolderName, statFN)==0 )
	{//if no new statistic folder name is given
		return false;
	}
}
//else change statistic folder name
//all files that are writen to the statistic folder change
bDirectParameterChanged=true;
bDistParameterChanged=true;
bNeibParameterChanged=true;

if (statisticFolderName) {delete [] statisticFolderName;}
statisticFolderName=new char[ strlen(statFN)+1 ];
strcpy(statisticFolderName,statFN);//copy string
return true;
}

bool cUniversNeib::setDirectBaseFileName( const char* dircBN )
/*set the direct base file name in wich the direct statistics should be saved and
creats the new file for all direct statistics in theas files
post: the pointer to direct base file name in wich the direct statistics should be
	saved
post: true if the value is changed, else false*/
{
if (!dircBN)
{//if no string is given, don't change
	return false;
}
if (directBaseName) 
{//realy new name
	if ( strcmp(directBaseName, dircBN)==0 )
	{//if no new direct-statistic file name is given
		return false;
	}
}
//else change direct-statistic file name
bDirectParameterChanged=true;
if (directBaseName) {delete [] directBaseName;}
directBaseName=new char[ strlen(dircBN)+1 ];
strcpy(directBaseName,dircBN);//copy string
return true;
}

bool cUniversNeib::setPartSizeFileName( const char* partN )
/*set the partsize file name in wich the part size of the actual univers
should be saved and creats the new file for part size statistics
post: the pointer to partsize file name in wich the partsize statistics
	should be saved
post: true if the value is changed, else false*/
{
if (!partN)
{//if no string is given, don't change
	return false;
}
if (partSizeName) 
{//realy new name
	if ( strcmp(partSizeName, partN)==0 )
	{//if no new partsize-statistic file name is given
		return false;
	}
}
//else change partsize-statistic file name
bPartSizeParameterChanged=true;
if (partSizeName) {delete [] partSizeName;}
partSizeName=new char[ strlen(partN)+1 ];
strcpy(partSizeName,partN);//copy string
return true;
}


bool cUniversNeib::setDistanceBaseFileName( const char* distBN )
/*set the distance base file name in wich the distance statistics should be saved and
creats the new file for all distance statistics in theas files
post: the pointer to distance base file name in wich the distance statistics should be
	saved
post: true if the value is changed, else false*/
{
if (!distBN)
{//if no string is given, don't change
	return false;
}
if (distBaseName) 
{//realy new name
	if ( strcmp(distBaseName, distBN)==0 )
	{//if no new distance-statistic file name is given
		return false;
	}
}
//else change distance-statistic file name
bDistParameterChanged=true;
if (distBaseName) {delete [] distBaseName;}
distBaseName=new char[ strlen(distBN)+1 ];
strcpy(distBaseName,distBN);//copy string
return true;
}

bool cUniversNeib::setNeibourBaseFileName( const char* neibBN )
/*set the neibour base file name in wich the neibour statistics should be saved and
creats the new file for all neibour statistics in theas files
post: the pointer to neibour base file name in wich the neibour statistics should be
	saved
post: true if the value is changed, else false*/
{
if (!neibBN)
{//if no string is given, don't change
	return false;
}
if (neibBaseName) 
{//realy new name
	if ( strcmp(neibBaseName, neibBN)==0 )
	{//if no new neibour-statistic file name is given
		return false;
	}
}
//else change neibour-statistic file name
bNeibParameterChanged=true;
if (neibBaseName) {delete [] neibBaseName;}
neibBaseName=new char[ strlen(neibBN)+1 ];
strcpy(neibBaseName,neibBN);//copy string
return true;
}

bool cUniversNeib::restoreGrid(const char* gFile)
/*loads the grid (list of point names) from the file with the
pathname gFile
pre: the pathname of the grid file
post: the loaded grid in this class instanze*/
{
ifstream gridF(gFile);
if (!gridF){return false;}
unsigned long nOP;
unsigned long tPoint;
char c;
gridN.clear();
gridF>>nOP;
gridF>>c;
for (unsigned int i=0;i<nOP;i++)
{
	gridF>>tPoint;
	gridF>>c;
	gridN.push_back(tPoint);
}
gridF.close();
return true;
}

bool cUniversNeib::storeGrid(const char* gFile)
/*writes the grid (list of point names) to the file with the pathname
gFile
pre: the pathname of the grid file
post: the stored grid in the file*/
{
ofstream gridF(gFile);
if (!gridF){return false;}
gridF<<gridN.size()<<';';
for (list<unsigned long>::iterator itr=gridN.begin();itr!=gridN.end();itr++)
	{gridF<<(*itr)<<";";}
gridF.close();
return true;
}

bool cUniversNeib::restoreParameter(const char* pFile)
/*loads the parameter from the file with the pathname pFile
pre: the pahtname of the parameter file
post: the loaded parameter in this class instanze*/
{
char *loadUnivers=0;//univers to load at the beginning

//open parameter file
ifstream paraF(pFile);
if (!paraF)
	{return false;}

//copy parameterfile name
if (parameterFile){delete [] parameterFile;}
parameterFile=new char[ strlen(pFile)+1 ];
strcpy(parameterFile,pFile);//copy string

//read parameterfile
cParameter actualParameter;
unsigned int line=1;//actual line in the parameterfile
list<cParameter>::iterator acItr;//actual parameter
for (unsigned int maxC=0 ; maxC<100000 ; line++,maxC++)
{
	//read number of Parameter
	actualParameter.number=readInt(paraF);
	//find parameter in parameterlist
	if (actualParameter.number)
	{
		for (acItr=parameter.begin();acItr!=parameter.end();acItr++)
		{
			if((acItr->number)==actualParameter.number){break;}
		}
	}
	bool inserted=false;
	if ((acItr==parameter.end())||(actualParameter.number==0))
	{//create new parameter entry
		acItr=parameter.insert(parameter.end(),actualParameter);
		inserted=true;
	}
	(acItr->line)=line;
	//read and store Parametertext
	char* actualParametertext=readChar(paraF);
	//check if readed value is valid
	if (inserted)
	{
		if (actualParametertext==NULL)
		{//if nothing was readed; end of file
			acItr=parameter.erase(acItr);
			delete actualParametertext;
			break;
		}
	}else{
		//this parameter was readed befor, don't create double parameter entries
		if (actualParametertext==NULL)
		{//if nothing was readed; end of file
			delete actualParametertext;
			break;
		}
		delete (acItr->name);//delete
	}
	(acItr->name)=actualParametertext;
	
	//set parameter value
	switch (acItr->number)//read parameter and the ';' char
	{
		case 1:{//read max time
			setMaxNumberOfTime(readInt(paraF));
			break;
		}
		case 2:{//read max points
			setMaxNumberOfPoints(readInt(paraF));
			break;
		}
		case 3:{//read the "check max points every ticks" parameter
			setCheckMaxPoints(readInt(paraF));
			break;
		}
		case 4:{//read basis time bTime
			setTimeBase(readInt(paraF));
			break;
		}
		case 5:{//read if the univers should be appended
			appendUnivers=readBool(paraF);
			break;
		}
		case 6:{//read the path of the to load univers
			loadUnivers=readPath(paraF);
			break;
		}
		case 7:{//read if the comments should be printed
			setCommentsActiv(readBool(paraF));
			break;
		}
		case 8:{//read how often the statistics should be outputed
			setOutStatisticCycle(readInt(paraF));
			break;
		}
		case 9:{//read the name of the statistic file
			char *szStatFN=readPath(paraF);
			if (szStatFN)
			{
				setStatisticFileName( szStatFN );
				delete [] szStatFN;
			}
			break;
		}
		case 10:{//read how often the universes should be outputed
			setOutUniversCycle(readInt(paraF));
			break;
		}
		case 11:{//read the name of the univers folder
			char* szUniFolder=readPath(paraF, true);
			if ( szUniFolder )
			{
				setUniversFolderName(szUniFolder);
				delete [] szUniFolder;
			}
			break;
		}
		case 12:{//read the name of the univers basename
			char* szUniBaseName=readPath(paraF);
			if ( szUniBaseName )
			{
				setUniversFileBaseName(szUniBaseName);
				delete [] szUniBaseName;
			}			
			break;
		}
		case 13:{//read how often the universes should be cuted
			setCutCycle(readInt(paraF));
			break;
		}
		case 14:{//read near wich dimension the universes should be cuted
			setCutNearDimension(readDouble(paraF));
			break;
		}
		case 15:{//read cut max class ratio
			setCutMaxClassRatio(readDouble(paraF));
			break;
		}
		case 16:{//read if the real time statistics should be outputed
			setOutRealTime(readInt(paraF));
			break;
		}
		case 17:{//read the name of the real time statistic file
			char* szRealTimeFN=readPath(paraF);
			if ( szRealTimeFN )
			{
				setRTimeFileName(szRealTimeFN);
				delete [] szRealTimeFN;
			}
			break;
		}
		case 18:{//read if the cut statistics should be outputed
			setOutCutStatistic(readInt(paraF));
			break;
		}
		case 19:{//read the name of the cut statistic file
			char* szCutFileName=readPath(paraF);
			if ( szCutFileName )
			{
				setCutFileName(szCutFileName);
				delete [] szCutFileName;
			}
			break;
		}
		//univers parameter end; neib parameter begin
		case 20:{//read how much points the univers should have befor the grid is created
			setGridAfterPoints(readInt(paraF));
			break;
		}
		case 21:{//read how much points the grid should have when it is created
			setNumberOfGridPoints(readInt(paraF));
			break;
		}
		case 22:{//read the minimum distance the grid points, in the created grid, should have
			setGridDistance(readInt(paraF));
			break;
		}
		case 23:{//read the position of the start point for the grid
			setGridStartPoint(readDouble(paraF));
			break;
		}
		case 24:{//read the name of the statistic folder
			char* szStatisticFolderName=readPath(paraF, true);
			if ( szStatisticFolderName )
			{
				setStatisticFolderName(szStatisticFolderName);
				delete [] szStatisticFolderName;
			}
			break;
		}
		case 25:{//read how often the maximal distance in the univers schould be evalued
			setGetPartSize(readInt(paraF));
			break;
		}
		case 26:{//read the name of the maximal distance file name
			char* szPartSizeFileName=readPath(paraF);
			if ( szPartSizeFileName )
			{
				setPartSizeFileName(szPartSizeFileName);
				delete [] szPartSizeFileName;
			}
			break;
		}
		case 27:{//read how often the direct statistic of the univers schould be evalued
			setDirectStatistics(readInt(paraF));
			break;
		}
		case 28:{//read the basename of the direct statistic
			char* szDirectBaseName=readPath(paraF);
			if ( szDirectBaseName )
			{
				setDirectBaseFileName(szDirectBaseName);
				delete [] szDirectBaseName;
			}
			break;
		}
		case 29:{//read how often the neibour statistic of the univers schould be evalued
			setNeibourStatistics(readInt(paraF));
			break;
		}
		case 30:{//read the basename of the neibour statistic
			char* szNeibourBaseName=readPath(paraF);
			if ( szNeibourBaseName )
			{
				setNeibourBaseFileName(szNeibourBaseName);
				delete [] szNeibourBaseName;
			}
			break;
		}
		case 31:{//read till wich distance the neibour statistic should be evalued
			setNeibourDistance(readInt(paraF));
			break;
		}
		case 32:{//read how often the distance statistic of the univers schould be evalued
			setDistanceStatistics(readInt(paraF));
			break;
		}
		case 33:{//read the basename of the distance statistic
			char* szDistanceBaseName=readPath(paraF);
			if ( szDistanceBaseName )
			{
				setDistanceBaseFileName(szDistanceBaseName);
				delete [] szDistanceBaseName;
			}
			break;
		}
		case 34:{//read if the part universes statistics should be outputed
			setOutUniversPartStatistic(readInt(paraF));
			break;
		}
		case 35:{//read the name of the part universes statistic file
			char* szUniversPartStatisticFileName=readPath(paraF);
			if ( szUniversPartStatisticFileName ){
				setUniversPartStatisticFileName(szUniversPartStatisticFileName);
				delete [] szUniversPartStatisticFileName;
			}
			break;
		}

		case 50:{//maximal period betwean the saves the universe
			timeMaxBetweanSaves=readPeriod(paraF);
			break;
		}
		case 51:{//maximal period betwean the iterations; if iteration takes to long stop evaluation
			timeMaxTimeIteration=readPeriod(paraF);
			break;
		}
		case 52:{//time in seconds the evaluation should maximal last
			timeMaxTime=readPeriod(paraF);
			break;
		}
/*		default:{//comment readed
			break;}*/
	}
}
paraF.close();
//sort lines; renumber lines
parameter.sort();
line=1;
for (acItr=parameter.begin();acItr!=parameter.end();acItr++){
	(acItr->line)=line;
	line++;
}

//load the spaceunivers to begin with
if ((loadUnivers)&&(loadUnivers[0]!=0)&&(checkPath(loadUnivers)))
{
	ifstream uFile(loadUnivers);
	if( uFile!= NULL )
	{
		readUnivers(uFile);
		uFile.close();
		
		//load eventual grid
		if ( appendUnivers && ((getDirect>0)||(getNeib>0)||(getDist>0)) )
		{//if univers is loaded and a grid could be created
			char gridFN[10000];//grid path
			sprintf(gridFN,"%sgrid.txt",statisticFolderName);
			restoreGrid(gridFN);
		}

	} else {
		printf( "Problem opening the univers file to read\n" );
		bEndEvaluation = true;
		return false;
	}
}

if (loadUnivers)
	{delete [] loadUnivers;}
return true;
}

bool cUniversNeib::storeParameter(const char* pFile)
/*writes the parameter to the file with the pathname pFile
pre: the pahtname of the parameter file
post: the stored parameter in the file*/
{
unsigned int line=1;//maximal chars to read; to avoid infinity loops
list<cParameter>::iterator acItr;
//sort lines; renumber lines
parameter.sort();
for (acItr=parameter.begin();acItr!=parameter.end();acItr++){
	(acItr->line)=line;
	line++;
}
ofstream paraF(pFile);
if (!paraF){return false;}
//delete all old comments
for (acItr=parameter.begin();acItr!=parameter.end();acItr++)
{
	//write number of Parameter
	paraF<<acItr->number;
	paraF<<".";//write the '.'
	//write Parametertext
	paraF<<(acItr->name);
	//set parameter value
	switch (acItr->number)//read parameter and the ';' char
	{
		case 1:{//write max time
			paraF<<":"<<getMaxNumberOfTime();
			break;
		}
		case 2:{//write max points
			paraF<<":"<<getMaxNumberOfPoints();
			break;
		}
		case 3:{//write the "check max points every ticks" parameter
			paraF<<":"<<getCheckMaxPoints();
			break;
		}
		case 4:{//write basis time bTime
			if(appendUnivers)
				{paraF<<":"<<bTime+iTime;}
				else{paraF<<":"<<getTimeBase();}
			break;
		}
		case 5:{//write if the univers should be appended
			paraF<<":"<<(appendUnivers ? "ja" : "nein");
			break;
		}
		case 6:{//write the path of the to load univers
			paraF<<":";
			if (iTime)
				{paraF<<getUniversFolderName()<<getUniversFileBaseName()<<(bTime+iTime)<<".txt";}
			break;
		}
		case 7:{//write if the comments should be printed
			paraF<<":"<<(getCommentsActiv() ? "ja" : "nein");
			break;
		}
		case 8:{//write how often the statistics should be outputed
			paraF<<":"<<getOutStatisticCycle();
			break;
		}
		case 9:{//write the name of the statistic file
			paraF<<":"<<getStatisticFileName();
			break;
		}
		case 10:{//write how often the universes should be outputed
			paraF<<":"<<getOutUniversCycle();
			break;
		}
		case 11:{//write the name of the univers folder
			paraF<<":"<<getUniversFolderName();
			break;
		}
		case 12:{//write the name of the univers basename
			paraF<<":"<<getUniversFileBaseName();
			break;
		}
		case 13:{//write how often the universes should be cuted
			paraF<<":"<<getCutCycle();
			break;
		}
		case 14:{//write near wich dimension the universes should be cuted
			paraF<<":"<<getCutNearDimension();
			break;
		}
		case 15:{//write cut max class ratio
			paraF<<":"<<getCutMaxClassRatio();
			break;
		}
		case 16:{//write if the real time statistics should be outputed
			paraF<<":"<<getOutRealTime();
			break;
		}
		case 17:{//write the name of the real time statistic file
			paraF<<":"<<getRTimeFileName();
			break;
		}
		case 18:{//write if the cut statistics should be outputed
			paraF<<":"<<getOutCutStatistic();
			break;
		}
		case 19:{//write the name of the cut statistic file
			paraF<<":"<<getCutFileName();
			break;
		}
		//univers parameter end; neib parameter begin
		case 20:{//write how much points the univers should have befor the grid is created
			paraF<<":"<<getGridAfterPoints();
			break;
		}
		case 21:{//write how much points the grid should have when it is created
			paraF<<":"<<getNumberOfGridPoints();
			break;
		}
		case 22:{//write the minimum distance the grid points, in the created grid, should have
			paraF<<":"<<getGridDistance();
			break;
		}
		case 23:{//write the position of the start point for the grid
			paraF<<":"<<getGridStartPoint();
			break;
		}
		case 24:{//write the name of the statistic folder
			paraF<<":"<<getStatisticFolderName();
			break;
		}
		case 25:{//write how often the maximal distance in the univers schould be evalued
			paraF<<":"<<getPartSizeStatistics();
			break;
		}
		case 26:{//write the name of the maximal distance file name
			paraF<<":"<<getPartSizeFileName();
			break;
		}
		case 27:{//write how often the direct statistic of the univers schould be evalued
			paraF<<":"<<getDirectStatistics();
			break;
		}
		case 28:{//write the basename of the direct statistic
			paraF<<":"<<getDirectBaseFileName();
			break;
		}
		case 29:{//write how often the neibour statistic of the univers schould be evalued
			paraF<<":"<<getNeibourStatistics();
			break;
		}
		case 30:{//write the basename of the neibour statistic
			paraF<<":"<<getNeibourBaseFileName();
			break;
		}
		case 31:{//write till wich distance the neibour statistic should be evalued
			paraF<<":"<<getNeibourDistance();
			break;
		}
		case 32:{//write how often the distance statistic of the univers schould be evalued
			paraF<<":"<<getDistanceStatistics();
			break;
		}
		case 33:{//write the basename of the distance statistic
			paraF<<":"<<getDistanceBaseFileName();
			break;
		}
		case 34:{//write if the part universes statistics should be outputed
			paraF<<":"<<getOutUniversPartStatistic();
			break;
		}
		case 35:{//write the name of the part universes statistic file
			paraF<<":"<<getUniversPartStatisticFileName();
			break;
		}
		
		case 50:{//maximal period betwean the saves the universe
			paraF<<":"<<(unsigned long)(timeMaxBetweanSaves);
			break;
		}
		case 51:{//maximal period betwean the iterations; if iteration takes to long stop evaluation
			paraF<<":"<<(unsigned long)(timeMaxTimeIteration);
			break;
		}
		case 52:{//time in seconds the evaluation should maximal last
			paraF<<":"<<(unsigned long)(timeMaxTime);
			break;
		}

	}
	paraF<<";"<<endl;//write ';' and the newline
}
paraF.close();
return true;
}



void cUniversNeib::printDirectGridHead()
/*prints the head of the direct all tabel */
{
if (directGridAll!=NULL){
	(*directGridAll)<<"univers ;size ;avarage points ; avarage all distances; avarage pos distances;";
	(*directGridAll)<<" avarage neg distances; avarage (pos-neg) distances; max points;";
	(*directGridAll)<<" max pos distances; max neg distances; max (pos-neg) distances;";
	(*directGridAll)<<" min points; min pos distances; min neg distances; min (pos-neg) distances;"<<endl;
}}


void cUniversNeib::printStatisticNeibourGridHead()
/*prints the head of the neibour all tabel */
{
if (neibGridAll!=NULL){
	(*neibGridAll)<<"univers; gridsize; avarage points; avarage pos distances; avarage neg distances;";
	(*neibGridAll)<<" avarage (pos-neg) distances; max points; max pos distances; max neg distances; max (pos-neg) distances;";
	(*neibGridAll)<<" min points; min pos distances; min neg distances; min (pos-neg) distances;"<<endl;
}}

void cUniversNeib::printStatisticDistGridHead()
/*prints the head of the dist all tabel */
{
if (distGridAll!=NULL){
	(*distGridAll)<<"univers; grid points; average distance betwean points; ";
	(*distGridAll)<<"max distance betwean points; secound minimal distance betwean points;"<<endl;
}}

void cUniversNeib::evalueDirectStatGrid(list<cPoint*> grid)
/*evalue the statistics of the grid, for each point in the grid the number of all, positiv, negativ, (positiv-negativ) distances and neibour points is printed
pre: the grid for wich the statistics should be evalued*/
{
unsigned int tmp=0,pos=0,neg=0,points=0,minPos=0,minNeg=0,minPoints=0,maxPos=0,maxNeg=0,maxPoints=0;
int posNeg=0,maxPosNeg=0,minPosNeg=0;
double averageAll=0.0,averagePos=0.0,averageNeg=0.0,averagePosNeg=0.0,averagePoints=0.0;
list<cPoint*>::iterator itr1;
//open statistic files, for statistic of this universes
char neibFND[1000];//number of pos neg distances to neibours around the grid points
sprintf(neibFND,"%s%sU%li.txt",statisticFolderName,directBaseName,(bTime+(long)iTime)); //statisticFolderName
ofstream nFileN(neibFND);
if (nFileN){
	nFileN<<"point; neibour points; all distances; pos distances; neg distances; pos-neg distances;"<<endl;
	for (list<cPoint*>::iterator itr=grid.begin();itr!=grid.end();itr++)
	{
		pos=((*itr)->pPoint).size();
		neg=((*itr)->nPoint).size();
		posNeg=int(pos)-int(neg);
		//count different points in each list (both list have no points of the other list)
		points=0;
		if (!(((*itr)->pPoint).empty()))
		{
			((*itr)->pPoint).sort(&cPoint::lower);
			itr1=((*itr)->pPoint).begin();
			tmp=(*itr1)->name; points++;
			for (;itr1!=((*itr)->pPoint).end();itr1++)
			{
				if (tmp!=((*itr1)->name))
					{tmp=(*itr1)->name; points++;}
			}
		}
		if (!(((*itr)->nPoint).empty()))
		{
			((*itr)->nPoint).sort(&cPoint::lower);
			itr1=((*itr)->nPoint).begin();
			tmp=(*itr1)->name; points++;
			for (;itr1!=((*itr)->nPoint).end();itr1++)
			{
				if (tmp!=((*itr1)->name))
					{tmp=(*itr1)->name; points++;}
			}
		}
		nFileN<<((*itr)->name)<<";"<<points<<";"<<pos+neg<<";"<<pos<<";"<<neg<<";"<<posNeg<<";"<<endl;
		averagePos+=pos;averageNeg+=neg;averagePosNeg+=posNeg;averagePoints+=points;averageAll+=pos+neg;
		if(itr==grid.begin()){maxPos=pos;maxNeg=neg;maxPosNeg=posNeg;minPos=pos;minNeg=neg;
			minPosNeg=posNeg;maxPoints=points;minPoints=points;}
		else{
			if(maxPos<pos){maxPos=pos;};
			if(maxNeg<neg){maxNeg=neg;};
			if(maxPosNeg<posNeg){maxPosNeg=posNeg;};
			if(minPos>pos){minPos=pos;};
			if(minNeg>neg){minNeg=neg;};
			if(minPosNeg>posNeg){minPosNeg=posNeg;}
			if(maxPoints<points){maxPoints=points;}
			if(minPoints>points){minPoints=points;}
		}
	}
	averagePos=averagePos/grid.size();averageNeg=averageNeg/grid.size();
	averagePosNeg=averagePosNeg/grid.size();averagePoints=averagePoints/grid.size();
	averageAll=averageAll/grid.size();
	nFileN<<"average ;"<<averagePoints<<" ;"<<averageAll<<" ;"<<averagePos<<" ;"<<averageNeg<<" ;"<<averagePosNeg<<"; "<<endl;
	nFileN<<"maximum ;"<<maxPoints<<" ;"<<maxPos<<" ;"<<maxNeg<<" ;"<<maxPosNeg<<"; "<<endl;
	nFileN<<"minimum ;"<<minPoints<<" ;"<<minPos<<" ;"<<minNeg<<" ;"<<minPosNeg<<"; "<<endl;
	nFileN.close();
}
if (directGridAll!=NULL){
	(*directGridAll)<<(bTime+iTime)<<" ;"<<(grid.size())<<" ;"<<averagePoints<<" ;";
	(*directGridAll)<<averageAll<<" ;"<<averagePos<<" ;"<<averageNeg<<" ;"<<averagePosNeg<<"; ";
	(*directGridAll)<<maxPoints<<" ;"<<maxPos<<" ;"<<maxNeg<<" ;"<<maxPosNeg<<"; ";
	(*directGridAll)<<minPoints<<" ;"<<minPos<<" ;"<<minNeg<<" ;"<<minPosNeg<<"; "<<endl;
}
}

void cUniversNeib::evalueGridDistance(list<cPoint*> grid)
/*evaluates the distance betwean the grid points and output them to the distance files
pre: the grid for wich the statistics should be evalued*/
{
/*print maximum 1000 points*/
#define MAX_DISTANCE_STATISTIC_POINTS 1000
const unsigned int uiNboOutputPoints = (grid.size()<=MAX_DISTANCE_STATISTIC_POINTS) ? grid.size() : MAX_DISTANCE_STATISTIC_POINTS;
unsigned int distances[uiNboOutputPoints][uiNboOutputPoints];
list<unsigned int> tmpDist;
unsigned int maxAll=0,min2All=0;
double average,averageAll=0;
//open statistic files, for statistic of this universes
char gridFND[1000];//distances betwean the grid points
sprintf(gridFND,"%s%sU%li.txt",statisticFolderName,distBaseName,(bTime+(long)iTime));
ofstream nFileD(gridFND);
if (nFileD)
{
	/*output tabele head*/
	nFileD<<"name; ";
	unsigned int uiNboPoint=0;
	list<cPoint*>::iterator itr;
	for (itr=grid.begin(), uiNboPoint=0; (itr!=grid.end()) && (uiNboPoint < uiNboOutputPoints) ; itr++ , uiNboPoint++)
	{//output point names
		nFileD<<(*itr)->name<<" ;";
	}
	if (grid.size()>MAX_DISTANCE_STATISTIC_POINTS)
	{//ther are more points then shown
		nFileD<<"...";
	}
	//extra rows
	nFileD<<"; maximum; average ;;;dist sorted : ; number of grid points : "<<uiNboOutputPoints<<"( out of "<<grid.size()<<");";
	//evalue nessesary distances
	unsigned int a=0,b=0;
	list<cPoint*>::iterator itr1;
	grid.sort(&cPoint::lower);
	list<cPoint*> tmpL;
	list<pair<cPoint*,long> > resultL;
	list<pair<cPoint*,long> >::iterator resultItr;
	//evale the distances
	for (itr=grid.begin(),a=0;(itr!=grid.end()) && (a<uiNboOutputPoints); itr++,a++)
	{
		tmpL.clear();
		for (itr1=grid.begin(),b=0;(itr1!=grid.end()) && (b<uiNboOutputPoints);itr1++,b++)
		{
			if (a>b){tmpL.push_back(*itr1);}//points to search the distance to
		}
		resultL=getDistanceToPoints((*itr), tmpL);//evalue distance to the points
		//set the values to the distance matrix
		for (itr1=grid.begin(),b=0;itr1!=grid.end();itr1++,b++){

			if (a==b){distances[a][b]=0;}
			else{
				if (a>b){
					for(resultItr=resultL.begin();resultItr!=resultL.end();resultItr++){
						if((resultItr->first)==(*itr1))
						{//if correct point add it to the matrix
							distances[a][b]=distances[b][a]=resultItr->second;
							resultItr=resultL.erase(resultItr);
							break;
						}
					}
				}
			}
		}
	}
	//make statistics and output it
	for (itr=grid.begin(),a=0;(itr!=grid.end()) && (a < uiNboOutputPoints);itr++,a++)
	{
		average=0;
		tmpDist.clear();
		nFileD<<endl<<(*itr)->name<<" ;";
		for (itr1=grid.begin(),b=0;(itr1!=grid.end()) && (b < uiNboOutputPoints);itr1++,b++){
			tmpDist.push_back(distances[a][b]);
			average+=double(distances[a][b]);
		}
		average=average/(double(uiNboOutputPoints));
		list<unsigned int>::iterator itr1;
		for (itr1=tmpDist.begin();itr1!=tmpDist.end();itr1++)
			{nFileD<<(*itr1)<<";";}
		tmpDist.sort();
		if(tmpDist.size()>1)
		{
			itr1=tmpDist.begin();itr1++;
			if ((min2All>(*itr1))||(itr==grid.begin()))
				{min2All=(*itr1);}//minimum2
		}
		itr1=tmpDist.end();itr1--;
		if((itr==grid.begin())||(maxAll<(*itr1)))
			{maxAll=(*itr1);}
		nFileD<<" ;"<<(*itr1)<<" ;"<<average<<" ;;;";
		for (itr1=tmpDist.begin();itr1!=tmpDist.end();itr1++)
			{nFileD<<(*itr1)<<";";}
		averageAll+=average;
	}
	nFileD<<endl;
	if (grid.size()>MAX_DISTANCE_STATISTIC_POINTS)
	{//ther are more points then shown
		nFileD<<"...";
	}
	nFileD.close();
}
if (distGridAll!=NULL){
	averageAll=averageAll/(double(uiNboOutputPoints));
	(*distGridAll)<<(bTime+iTime)<<" ;";
	(*distGridAll)<<uiNboOutputPoints<<"(out of "<<(grid.size())<<") ; "<<averageAll<<" ; "<<maxAll<<" ; "<<min2All<<" ; "<<endl;
}
}

void cUniversNeib::evalueGridNeibour(list<cPoint*> grid)
/*evalue the neibourhood of the grid points till neibDist distance
pre: the grid for wich the statistics should be evalued*/
{
list<cPoint*> area;
unsigned int pos,neg,maxPos,maxNeg,minPos,minNeg,maxPoints,minPoints;
int posNeg,maxPosNeg,minPosNeg;
double averageNPos,averageNNeg,averageNPosNeg,averagePoints;
//open statistic files, for statistic of this universes
char neibFND[1000];//number of pos neg distances to neibours around the grid points
sprintf(neibFND,"%s%sU%li.txt",statisticFolderName,neibBaseName,(bTime+(long)iTime));
ofstream nFileN(neibFND);
if (nFileN){
	nFileN<<"name; points; pos  distances; neg distances; pos-neg distances;"<<endl;
	averageNPos=0;averageNNeg=0;averageNPosNeg=0;averagePoints=0;
	for (list<cPoint*>::iterator itr=grid.begin();itr!=grid.end();itr++)
	{
		area=getNeigbours((*itr),neibDist);
		pos=getNumberOfPosDistances(area);
		neg=getNumberOfNegDistances(area);
		posNeg=int(pos)-int(neg);
		nFileN<<(*itr)->name<<" ;"<<area.size()<<" ;"<<pos<<" ;"<<neg<<" ;"<<posNeg<<" ;"<<endl;
		if(itr==grid.begin()){maxPos=pos;maxNeg=neg;maxPosNeg=posNeg;minPos=pos;minNeg=neg;
			minPosNeg=posNeg;maxPoints=area.size();minPoints=area.size();}
		else{
			if(maxPos<pos){maxPos=pos;};
			if(maxNeg<neg){maxNeg=neg;};
			if(maxPosNeg<posNeg){maxPosNeg=posNeg;};
			if(minPos>pos){minPos=pos;};
			if(minNeg>neg){minNeg=neg;};
			if(minPosNeg>posNeg){minPosNeg=posNeg;}
			if(maxPoints<area.size()){maxPoints=area.size();}
			if(minPoints>area.size()){minPoints=area.size();}
		}
		averageNPos+=pos;averageNNeg+=neg;averageNPosNeg+=posNeg;averagePoints+=area.size();
	}
	averageNPos=averageNPos/grid.size();averageNNeg=averageNNeg/grid.size();
	averageNPosNeg=averageNPosNeg/grid.size();averagePoints=averagePoints/grid.size();
	nFileN<<"average ;"<<averagePoints<<" ;"<<averageNPos<<" ;"<<averageNNeg<<" ;"<<averageNPosNeg<<"; "<<endl;
	nFileN<<"maximum ;"<<maxPoints<<" ;"<<maxPos<<" ;"<<maxNeg<<" ;"<<maxPosNeg<<"; "<<endl;
	nFileN<<"minimum ;"<<minPoints<<" ;"<<minPos<<" ;"<<minNeg<<" ;"<<minPosNeg<<"; "<<endl;
	nFileN.close();
}
if ( neibGridAll!=NULL ){
	(*neibGridAll)<<(bTime+iTime)<<" ;"<<(grid.size())<<" ;"<<averagePoints<<" ;";
	(*neibGridAll)<<averageNPos<<" ;"<<averageNNeg<<" ;"<<averageNPosNeg<<" ;";
	(*neibGridAll)<<maxPoints<<" ;"<<maxPos<<" ;"<<maxNeg<<" ;"<<maxPosNeg<<" ;";
	(*neibGridAll)<<minPoints<<" ;"<<minPos<<" ;"<<minNeg<<" ;"<<minPosNeg<<" ;"<<endl;
}
}

void cUniversNeib::evaluePartSize()
/*get the size of the Part univers in wich the Point orgin is to the point orgin,
	this means the greatest minimal distance to a point in the part univers*/
{
if( partSizeF!=NULL)
	{(*partSizeF)<<(bTime+iTime)<<" ;"<<getUniversPartSize(*univers.begin())<<" ;"<<endl;}
}


bool cUniversNeib::outputCondition()
/*evaluates if the actual univers should be outputed
post: true if the univers should be outputed; else false*/
{
if (outUniv) if ( (bTime+iTime)%outUniv == 0 )
	{return true;}
if (timeMaxBetweanSaves) if ( time(0) - timeOfLasteSave > timeMaxBetweanSaves )
	{return true;}
return false;
}

bool cUniversNeib::endCondition() const
/*Evalues the end condition for the univers. Means when the evaluation of
the univers is stoped.
case 1: the time iTime is higer than the maximum number of ticks(maxTime,
	maxTime=0 -> inf) or (the number of points should be checked (it is the
	checkMaxPoints tick) and it is higher then the maximal number of points
	(maxPoints, maxPoints=0 -> inf))
post: true if the end condition holds and the univers should be stoped,
	else false*/
{
if (cUnivers::endCondition())
	{return true;}
//dit the iteration takes to long
if ( timeMaxTimeIteration )
	if ( time(0) - timeOfIterationBegin > timeMaxTimeIteration )
		{return true;}
//maximal time for evaluation reached
if ( timeMaxTime )
	if ( time(0) - timeOfBegin > timeMaxTime)
		{return true;}
return false;//don't stop
}

void cUniversNeib::start(unsigned long trans)
/*Starts the evaluation of the univers. Makes ticks till the end condition
holds.
post: the this univers changed*/
{
char c=0;
#ifdef linux
cKeyboard kb;
#endif
time_t lRTime=time(0),aRTime;
time_t evTime,cutTime,partTime,outUTime,dirTime,neibTime,distTime,partSTime;
tm *aRTm;
bool bStopIteration=false;
timeOfBegin=time(0);
timeOfIterationBegin=time(0);

if (endCondition())
	{return;}//end condition reached befor first iteration
	
initUnivers();

timeOfLasteSave=time(0);
while( ! bStopIteration )
{
	iTime++;
	timeOfIterationBegin=time(0);
	
	if (trans) {tick(trans);}
		else{tick();}
	evTime=time(0);
	if(outComent)
	{
		outputStatistic();
	}
	if(cutAfter) if ( (bTime+iTime)%cutAfter == 0 )//dont cut every time
	{//cut univers
		cutUnivers(cutNearDimension, cutMaxClassRatio);
		if(outComent)
		{
			outputStatistic();
		}
	}
	
	cutTime=time(0);
	if (lOutUniversPartStatistic) if ( (bTime+iTime)%lOutUniversPartStatistic == 0 ){
		evaluePartStatistic();
	}
	
	partTime=time(0);
	if (outStat) if ( (bTime+iTime)%outStat == 0 ){
		printStatistic( *statFile );
	}
	
	if ( outputCondition() )
	{//output actual universe
		char univFile[1000];
		sprintf(univFile,"%s%s%li.txt",uFolder,bUName,bTime+(long)iTime);
		ofstream uFile(univFile);
		if(uFile)
		{
			printUnivers(uFile);
			uFile.close();
			timeOfLasteSave=time(0);
		}else {printf( "Problem opening the univers file\n" );}
	}
	outUTime=time(0);
	
	if(gridN.empty()&&(gridPoints>0)&&((getDirect>0)||(getNeib>0)||(getDist>0))){
		if (gridAfterPoints<getNumberOfPoints()){
			//make the grid
			if(outComent) {cout<<"creating grid : ";}
			if ( cutAfter && !( (bTime+iTime)%cutAfter == 0))
				{cutUnivers(cutNearDimension, cutMaxClassRatio);}
			if(outComent)
			{
				cout<<" points: "<<getNumberOfPoints()<<" pos distances : "<<pDistance;
				cout<<" neg distances : "<<nDistance<<" distances/points : "<<((double)(pDistance+nDistance)/(double)(getNumberOfPoints()))<<endl;
			}
			unsigned long startGP=((unsigned long)(double(univers.size()) * (gridStartPoint)));
			list<cPoint*>::iterator startP=univers.begin();
			for (unsigned long i=0;i<startGP;i++)
				{startP++;}
			list<cPoint*> grid=makeGrid((*startP),gridDist,gridPoints);
			for (list<cPoint*>::iterator itr=grid.begin();itr!=grid.end();itr++)
				{gridN.push_back((*itr)->name);}
			gridN.sort();
		}
	}
	if (!(gridN.empty())&&((getDirect>0)||(getNeib>0)||(getDist>0)))
	{
		//get points of new univers for the grid
		list<cPoint*> grid=findPoints(gridN);
		if (grid.size()<gridN.size())
		{
			gridN.clear();
			for (list<cPoint*>::iterator itr=grid.begin();itr!=grid.end();itr++)
				{gridN.push_back((*itr)->name);}
		}
		if (!(gridN.empty()))
		{
			if (getDirect) if ( (bTime+iTime)%getDirect == 0 )
				{evalueDirectStatGrid(grid);}
			dirTime=time(0);
			if (getNeib) if ( (bTime+iTime)%getNeib == 0 )
				{evalueGridNeibour(grid);}
			neibTime=time(0);
			if (getDist) if ( (bTime+iTime)%getDist == 0 )
				{evalueGridDistance(grid);}
			distTime=time(0);
		}
	}
	if (getPartSize) if ( (bTime+iTime)%getPartSize== 0 ){
		evaluePartSize();
		partSTime=time(0);
	}
		
	if (outRealTime&&(rTimeFile)) if ((bTime+iTime)%outRealTime == 0 )
	{//output real time statistic
		aRTime=time(0);
		aRTm=localtime(&aRTime);
		(*rTimeFile)<<bTime+iTime<<" ; ";
		(*rTimeFile)<<aRTm->tm_mday<<"."<<aRTm->tm_mon + 1<<"."<<1900+aRTm->tm_year<<"  ";
		(*rTimeFile)<<aRTm->tm_hour<<":"<<aRTm->tm_min<<":"<<aRTm->tm_sec<<" ; ";
		
		(*rTimeFile)<<difftime(aRTime,lRTime)<<"; "<<difftime(evTime,lRTime)<<"; ";
		
		if((cutAfter)&&(((bTime+iTime)/cutAfter)*cutAfter==(bTime+iTime))){
			(*rTimeFile)<<difftime(cutTime,evTime)<<"; ";
		}else{(*rTimeFile)<<"0; ";}
		
		if((outUniv)&&(((bTime+iTime)/outUniv)*outUniv==(bTime+iTime))){
			(*rTimeFile)<<difftime(outUTime,partTime)<<"; ";
		}else{(*rTimeFile)<<"0; ";}
		
		if(!(gridN.empty())&&(getDirect)){
			(*rTimeFile)<<difftime(dirTime,outUTime)<<"; ";
		}else{(*rTimeFile)<<"0; ";}
		if(!(gridN.empty())&&(getNeib)){
			(*rTimeFile)<<difftime(neibTime,dirTime)<<"; ";
		}else{(*rTimeFile)<<"0; ";}
		if(!(gridN.empty())&&(getDist)){
			(*rTimeFile)<<difftime(distTime,neibTime)<<"; ";
		}else{(*rTimeFile)<<"0; ";}
		if((getPartSize)){
			if(!(gridN.empty()))
				{(*rTimeFile)<<difftime(partSTime,distTime)<<"; ";}
			else{(*rTimeFile)<<difftime(partSTime,outUTime)<<"; ";}
		}else{(*rTimeFile)<<"0; ";}
		
		if ((lOutUniversPartStatistic) && ( (bTime+iTime)%lOutUniversPartStatistic == 0 )){
			(*rTimeFile)<<difftime(partTime,cutTime)<<"; ";
		}else{(*rTimeFile)<<"0; ";}
		
		(*rTimeFile)<<endl;
		lRTime=aRTime;
	}
#ifdef linux
	while (kb.kbhit())
	{//end evaluation?
		c=kb.getch();
#else
	while (kbhit())
	{//end evaluation?
		c=getch();
#endif
		cout<<endl<<endl<<"C for Chancel"<<endl;
		cout<<"E for End"<<endl;
		cout<<"key pressed :"<<c<<endl;//<<" Nummer :"<<int(c)
		if((c=='E')||(c=='C')||(int(c)==3))
			{bStopIteration=true;}//end evaluation
		if (c=='C')//don't append if 'C' is pressed
			{appendUnivers=false;}
	}
	
	if( endCondition() )
		{bStopIteration=true;}//end evaluation	
		
	if((bStopIteration)&&(appendUnivers)&&(parameterFile))//safe parameter, univers and grid
	{//save the aktual position so it can restored later		
		if( ! outputCondition() )
		{
			char univFile[1000];
			sprintf(univFile,"%s%s%li.txt",uFolder,bUName,bTime+(long)iTime);
			ofstream uFile(univFile);
			if( uFile!= NULL )
			{
				printUnivers(uFile);
				uFile.close();
			}else {printf( "Problem opening the univers file\n" );}
		}
		storeParameter(parameterFile);
		if ((getDirect)||(getNeib)||(getDist))
		{
			char gridFN[1000];//grid path
			sprintf(gridFN,"%sgrid.txt",statisticFolderName);
			storeGrid(gridFN);
		}
		if(outComent)
		{
			cout<<endl<<"Berechnung erfolgreich beendet"<<endl;
		}
	}
}
}


int cUniversNeib::initUnivers()
/*init the enviroment of the univers;
crates directoris for statistics und other output
post: 0 if all inits are OK;
	the number of faild initialisations is returned;
	for failed initialisations the bXXXChanged-Variable is true*/
{
int iFailed=0;
//create statistic folder
if (  (outStat)   || (outRealTime) || (outCutStatistic) || (lOutUniversPartStatistic)
	|| (getDirect) || (getDist)     || (getNeib) )
	{cratePath( getStatisticFolderName() );}
	
iFailed += cUnivers::initUnivers();

//init partsize-statistic
if ( bPartSizeParameterChanged )
{//close old file and open or reopen partsize-file

	bPartSizeParameterChanged=false;
	if ( partSizeF )
	{//close old file
		partSizeF->close();
		delete partSizeF;
		partSizeF = NULL;
	}
	
	if ( getPartSize && partSizeName )
	{//open or reopen partsize-file
		bool bOpenExistingFile=false;
		
		if ( appendUnivers )
		{//try to reopen existing partsize-file
			bOpenExistingFile=checkPath(partSizeName) ;
		}
			
		if ( bOpenExistingFile )
		{//reopen file
			partSizeF=new fstream(partSizeName);
		}else{
			partSizeF=new fstream(partSizeName,ios::out);
		}
		if ( partSizeF )
		{
			if( bOpenExistingFile && searchForLine( partSizeF, ((getTimeBase()/getPartSize)*getPartSize),2 ) )
			{//append after last writen line
				(*partSizeF)<<endl;
			}else{ 
				(*partSizeF)<<"univers; partsize;"<<endl;
			}
		}else{//error occoured
			iFailed++;
			bPartSizeParameterChanged=true;
			if(outComent)
			{
				cout<<endl<<"Fehler beim Oeffnen der Partsize-Datei"<<endl;
			}
		}
	}
}

//init direct-statistic
if ( bDirectParameterChanged )
{//close old file and open or reopen direct-file

	bDirectParameterChanged=false;
	if ( directGridAll )
	{//close old file
		directGridAll->close();
		delete directGridAll;
		directGridAll = NULL;
	}
	
	if ( getDirect && directBaseName )
	{//open or reopen direct-file
		bool bOpenExistingFile=false;
		
		//create direct-statistic-path
		char tDirect[10000];
		sprintf(tDirect,"%s%sUAll.txt",statisticFolderName,directBaseName);
		
		if ( appendUnivers )
		{//try to reopen existing direct-file
			bOpenExistingFile=checkPath(tDirect) ;
		}
			
		if ( bOpenExistingFile )
		{//reopen file
			directGridAll=new fstream(tDirect);
		}else{
			directGridAll=new fstream(tDirect,ios::out);
		}
		if ( directGridAll )
		{
			if( bOpenExistingFile && searchForLine( directGridAll, ((getTimeBase()/getDirect)*getDirect),15 ) )
			{//append after last writen line
				(*directGridAll)<<endl;
			}else{ 
				printDirectGridHead();
			}
		}else{//error occoured
			iFailed++;
			bDirectParameterChanged=true;
			if(outComent)
			{
				cout<<endl<<"Fehler beim Oeffnen der Direktstatistik-Datei"<<endl;
			}
		}
	}
}

//init neibour-statistic
if ( bNeibParameterChanged )
{//close old file and open or reopen neibour-file

	bNeibParameterChanged=false;
	if ( neibGridAll )
	{//close old file
		neibGridAll->close();
		delete neibGridAll;
		neibGridAll = NULL;
	}
	
	if ( getNeib && neibBaseName )
	{//open or reopen neibour-file
		bool bOpenExistingFile=false;
		
		//create neibour-statistic-path
		char szNeibourPath[10000];
		sprintf(szNeibourPath,"%s%sUAll.txt",statisticFolderName,neibBaseName);
		
		if ( appendUnivers )
		{//try to reopen existing neibour-file
			bOpenExistingFile=checkPath(szNeibourPath) ;
		}
			
		if ( bOpenExistingFile )
		{//reopen file
			neibGridAll=new fstream(szNeibourPath);
		}else{
			neibGridAll=new fstream(szNeibourPath,ios::out);
		}
		if ( neibGridAll )
		{
			if( bOpenExistingFile && searchForLine( neibGridAll, ((getTimeBase()/getNeib)*getNeib),14 ) )
			{//append after last writen line
				(*neibGridAll)<<endl;
			}else{ 
				printStatisticNeibourGridHead();
			}
		}else{//error occoured
			iFailed++;
			bNeibParameterChanged=true;
			if(outComent)
			{
				cout<<endl<<"Fehler beim Oeffnen der Direktstatistik-Datei"<<endl;
			}
		}
	}
}
	
//init distance-statistic
if ( bDistParameterChanged )
{//close old file and open or reopen distance-file

	bDistParameterChanged=false;
	if ( distGridAll )
	{//close old file
		distGridAll->close();
		delete distGridAll;
		distGridAll = NULL;
	}
	
	if ( getDist && distBaseName )
	{//open or reopen distance-file
		bool bOpenExistingFile=false;
		
		//create distance-statistic-path
		char szDistancePath[10000];
		sprintf(szDistancePath,"%s%sUAll.txt",statisticFolderName,distBaseName);
		
		if ( appendUnivers )
		{//try to reopen existing distance-file
			bOpenExistingFile=checkPath(szDistancePath) ;
		}
			
		if ( bOpenExistingFile )
		{//reopen file
			distGridAll=new fstream(szDistancePath);
		}else{
			distGridAll=new fstream(szDistancePath,ios::out);
		}
		if ( distGridAll )
		{
			if( bOpenExistingFile && searchForLine( distGridAll, ((getTimeBase()/getDist)*getDist),5 ) )
			{//append after last writen line
				(*distGridAll)<<endl;
			}else{ 
				printStatisticDistGridHead();
			}
		}else{//error occoured
			iFailed++;
			bDistParameterChanged=true;
			if(outComent)
			{
				cout<<endl<<"Fehler beim Oeffnen der Distanzstatistik-Datei"<<endl;
			}
		}
	}
}	
	
return iFailed;
}













