#include <fstream>
#include "result_table.h"

using namespace std;

/**
 * a constructor
 */
result_table::result_table(int p_rows) {
  rows = p_rows;
  table = new struct table_row [rows];
}

/**
 * updates a table row
 */
int result_table::update_row(int p_row, float p_avg_fitness,
    float p_best_fitness, float p_divergency, float p_elite) {
  // add the parameter values to the given row members
  table[p_row].updates++;
  table[p_row].avg_fitness += p_avg_fitness;
  table[p_row].best_fitness += p_best_fitness;
  table[p_row].divergency += p_divergency;
  table[p_row].elite += p_elite;

  // return the row number, if only for the appearance's sake
  return p_row;
}

/**
 * prints a table into a file in a gnuplot-compatible format
 */
int result_table::print(char *p_filename) {
  // check the parameter
  if(p_filename == 0) return RT_NO_FILENAME_GIVEN;

  // open the input file
  ofstream out_file;
  out_file.open(p_filename);

  if(!out_file.is_open()) return RT_FILE_ERROR;

  // print the table to the file
  out_file << "# This file contains a statistical information\n";
  out_file << "# on an evolution of a CA-based population";
  out_file << endl << endl;
  out_file << "# Generation; Avg. Fitness; Best Fitness; Population \
Divergency; Elite Share" << endl;

  for(int i = 0; i < rows; i++) {
    out_file.width(4);
    out_file << i << '\t';

    int tmp = table[i].updates;

    out_file.width(10);
    out_file << (table[i].avg_fitness / tmp) << '\t';

    out_file.width(10);
    out_file << (table[i].best_fitness / tmp) << '\t';

    out_file.width(10);
    out_file << (table[i].divergency / tmp) << '\t';

    out_file.width(10);
    out_file << (table[i].elite / tmp) << endl;
  }

  // close the file
  out_file.close();
}

