#include "libscl.h"

using namespace scl;
using namespace std;


void do_not_exit(string msg)
{
  cout << msg << '\n';
}


int main(int argc, char** argp, char** envp)
{

  LIB_ERROR_HANDLER_PTR default_error;
  LIB_WARN_HANDLER_PTR default_warn;

  default_error = set_lib_error_handler(&do_not_exit);
  default_warn = set_lib_warn_handler(&do_not_exit);

  string filename;
  ifstream fin;
  ofstream fout;

  filename = "DCFdatayp.dat";

  fin.open(filename.c_str());
  if (!fin) error("Error, cannot open " + filename);

  realmat data;

  INTEGER count = readtable(fin,data);
  cout << count << '\n';

  realmat data_save = data;

  //cout << data;

  filename = "test_00.dat";
  fout.open(filename.c_str());
  if (!fout) error("Error, cannot open " + filename);

  count = writetable(fout,data,10,5);
  cout << count << '\n';

  //cout << count << '\n';

  fout.clear(); fout.close();

  filename = "test_01.dat";

  count = writetable(filename.c_str(),data,10,5);
  cout << count << '\n';

  vector<string> header;

  count = readtable(filename.c_str(),data,header);
  cout << count << '\n';

  count = readtable(filename.c_str(),data);
  cout << count << '\n';

  filename = "test_02.dat";
  
  header.clear();
  header.push_back("year");
  header.push_back("mrs");
  header.push_back("del_gdp");
  header.push_back("gdp-cp");
  header.push_back("del_cp");

  count = writetable(filename.c_str(),data,header,10,5);
  cout << count << '\n';

  count = readtable(filename.c_str(),data);  
  cout << count << '\n';

  count = readtable(filename.c_str(),data,header);  
  cout << count << '\n';

  for(vector<string>::const_iterator p=header.begin(); p<header.end(); ++p) {
    cout << *p << ' ';
  }
  cout << '\n';

  REAL max_err = -REAL_MAX;
  for (INTEGER i=1; i<=data.size(); ++i) {
    REAL err = fabs(data[i] - data_save[i]);
    max_err = err > max_err ? err : max_err;
  }

  cout << max_err << '\n';

  filename = "test_03.dat";

  count = writetable(filename.c_str(),data,header,10,5,'i');
  cout << count << '\n';

  count = writetable(filename.c_str(),data,header,10,5,'g');
  cout << count << '\n';

  filename = "test_04.dat";

  count = writetable(filename.c_str(),data,header,12,5,'e');
  cout << count << '\n';
   
  filename = "test_05.dat";

  count = writetable(filename.c_str(),data,header,12,5,'E');
  cout << count << '\n';
   
  return 0;
}
