/*Methods for the statistics gathering and displaying object.*/

#include <stdio.h>
#include "nullLewstats.h"
#include "string.h"

#ifndef MAXLINELENGTH
#define MAXLINELENGTH 80
#endif

cStats::cStats()
{	
	longeHist = new cHistogram;
	
	logfp = NULL;
	ave_longe = 0;
	ave_mutat = 0;

}

cStats::~cStats()
{
	fclose(logfp);
}

void cStats::open_file(char logfile[]) {logfp = fopen(logfile, "w");}

void cStats::close_file() 
{
	if (logfp != NULL) 
		fclose(logfp);
}

void cStats::setup(int popsize)
{
	char title[MAXLINELENGTH];
	char xlable[MAXLINELENGTH];
	char ylable[MAXLINELENGTH];

	strcpy(title, "Longevities"); 
/*	strcpy(xlable, "\plongevity");
	strcpy(ylable, "\p# orgs");

	longeHist->setup(title, xlable, ylable, NUM_LONGE_GROUPS, popsize, 0,
						 355, 40, 2, 1);
*/
}

		/*Takes the population and gathers the stats.*/	
void cStats::gather_pop(cPopulation *pop)
{

}


  /*I want to keep track of the time step, average fitness, average longevity
  	and average mutation*/
void cStats::record_state(cPopulation *pop, cContext *context)
{
	calc_ave_longe(pop->orgs, pop->numorgs);
	calc_ave_mutat(pop->orgs, pop->numorgs);
	calc_ave_age(pop->orgs, pop->numorgs);
	get_fitness_bounds(pop->orgs, pop->numorgs);
	
	fprintf(logfp, "%u\t%f\t%d\t%d\t%f\t%f\t%f\n", context->time_step, pop->ave_fitness, 
				max_fitness, min_fitness, ave_longe, ave_mutat, ave_age);
}

void cStats::display()  /*Plots the histograms of the stats.*/
{

}


/* Protected methods -------------------------------------------*/

void cStats::calc_ave_longe(cOrganism **orgs, int popsize)
{
	int i;
	
	ave_longe = 0;
	for(i=0; i < popsize; i++)
		ave_longe += (double) orgs[i]->get_longevity();
		
	ave_longe = ave_longe / popsize;
}

void cStats::calc_ave_mutat(cOrganism **orgs, int popsize)
{
	int i;
	
	ave_mutat = 0;
	for(i=0; i < popsize; i++)
		ave_mutat += (double) orgs[i]->get_mutation();
		
	ave_mutat = ave_mutat / popsize;

}

void cStats::calc_ave_age(cOrganism **orgs, int popsize)
{
	int i;
	
	ave_age = 0;
	for(i=0; i < popsize; i++)
		ave_age += (double) orgs[i]->get_age();
		
	ave_age = ave_age / popsize;

}


void cStats::get_fitness_bounds(cOrganism **orgs, int popsize)
{
	int i, a_fit;
	
	min_fitness = orgs[0]->get_fitness();
	max_fitness = min_fitness;
	
	for(i=1; i < popsize; i++)
	{
		if ((a_fit = orgs[i]->get_fitness()) > max_fitness) 
			max_fitness = a_fit;
		
		if (a_fit < min_fitness) 
			min_fitness = a_fit;
	}
}



void cStats::gather_longes(cOrganism **orgs)
{

}


void cStats::gather_mutats(cOrganism **orgs)
{

}


void cStats::gather_ages(cOrganism **orgs)
{

}