#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <tuple>
#include <list>
#include <algorithm>
#include "lineFitter.h"
#include "lineFitter_emxAPI.h"

using namespace std;


static emxArray_real_T *setupArray(list<double> &lis)
{
  emxArray_real_T *result;
  double *result_data;
  int i = (int)lis.size();
  int idx0;
  // Set the size of the array.

  result = emxCreateND_real_T(1, &i);
  result_data = result->data;

  // Copy the input data into our array
  copy(lis.begin(), lis.end(), result->data);
  
  return result;
}



int main(int argc, char *argv[]) {

  // Ensure there's a filename argument
  if(argc != 2) {
    cerr << "Usage: myFit.exe <filename>" << endl;
    return -1;
  }
  
  // Grab the filename and open the file
  string filename(argv[1]);
  ifstream fin(filename);

  // Make sure the file exists
  if(!fin) {
    cerr << "File \"" << filename << "\" not found." << endl;
    return -1; 
  }

  // Storage for the data columns
  list<double> xlis;
  list<double> ylis;
  double xin, yin;
  string line;

  // Read the data from the csv file (two columns with comma between)
  while(getline(fin, line)) {

    // Remove commas from the line
    replace(line.begin(), line.end(), ',', ' ');

    // Parse the string into xin and yin
    stringstream ss(line);
    ss >> xin >> yin;
    // Append to the input lists
    xlis.push_back(xin);
    ylis.push_back(yin);
  }

  // variables to solve for
  double b, m;
  
  /* Initialize function 'lineFitter' input arguments x and y. */
  emxArray_real_T *x = setupArray(xlis);
  emxArray_real_T *y = setupArray(ylis);
  
  /* Call the entry-point 'lineFitter'. */
  lineFitter(x, y, &m, &b);

  cout << "m,b = " << m << ", " << b << endl; 

  /* Free the arrays*/
  emxDestroyArray_real_T(y);
  emxDestroyArray_real_T(x);
  return 0;
  
}