#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cmath>
#include "interpolation.h"

using namespace std;
using namespace alglib;


double reversecalc4(double y, double a, double b, double c, double d)
{
//    return  c * pow((y - a) / (d - y), 1.0 / b);
    return  c * pow((a - d) / (y - d) - 1.0, 1.0 / b);
}


int main(int argc, char **argv)
{
    real_1d_array x;
    real_1d_array y;
    ae_int_t n = 0;
    double a = 0.0;
    double b = 30.0;
    double c = 19.5;
    double d = 1.0;
    double g;
    lsfitreport rep;

    if (argc < 2)
    {
        cout << "Missing input file" << endl;
        exit(1);
    }

    ifstream csvfile(argv[1]);
    if (!csvfile.is_open())
    {
        cout << "Unable to open " << argv[1] << endl;
        exit(1);
    }

    string line;
    double* xarray = new double[500];
    double* yarray = new double[500];
    double xval;
    double yval;
    char separator;

    while (getline(csvfile, line))
    {
        cout << line << endl;
        istringstream in(line);
        if ((in >> xval >> separator >> yval) && (separator == ','))
        {
            xarray[n] = xval;
            yarray[n] = yval;
            n++;
        }
    }
    csvfile.close();
    x.setcontent(n, xarray);
    y.setcontent(n, yarray);
    delete [] xarray;
    delete [] yarray;

    //
    // Use logisticfit4() to calculate the 4PL parameters
    //
    logisticfit4(x, y, n, a, b, c, d, rep);
    //logisticfit45x(x, y, n, alglib::fp_nan, alglib::fp_nan, true, 0.0, 0.0, 0, a, b, c, d, g, rep);

    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    cout << "c = " << c << endl;
    cout << "d = " << d << endl;

    cout << "iterations = " << rep.iterationscount << endl;
    cout << "RMS error = " << rep.rmserror << endl;
    cout << "Avg error = " << rep.avgerror << endl;
    cout << "Avg relative error = " << rep.avgrelerror << endl;
    cout << "Max error = " << rep.maxerror << endl;
    cout << "R squared = " << rep.r2 << endl;

    //
    // Evaluate model at points
    //
    cout << "calc x at 0.25 = " << reversecalc4(0.25, a, b, c, d) << endl;
    cout << "calc x at 0.50 = " << reversecalc4(0.5, a, b, c, d) << endl;
    cout << "calc x at 0.75 = " << reversecalc4(0.75, a, b, c, d) << endl;
    cout << "calc x at 1.00 = " << reversecalc4(1.0, a, b, c, d) << endl;

    return 0;
}
