/*
       Computes the linear regression for a series of measurements, the
       x-axis intercept of the regression line and its confidence interval, and
       writes a couple of files from which a nice plot of all this can be
       generated using the gnuplot program.
  */
  bool computeRegressionAndWriteGnuplotFiles_(vector<double>::const_iterator const conc_vec_begin,
                                              vector<double>::const_iterator const conc_vec_end,
                                              vector<double>::const_iterator const area_vec_begin,
                                              double const confidence_p,
                                              String const filename_prefix,
                                              String const output_filename,
                                              String const format = "",
                                              bool const write_gnuplot = true
                                              )
  {

    try
    {
      LinearRegression linreg;
      linreg.computeRegression(confidence_p, conc_vec_begin, conc_vec_end, area_vec_begin);

      if (write_gnuplot)
      {

        // the peak data goes here
        String datafilename(filename_prefix);
        datafilename += String(".dat");
        ofstream dataout(datafilename.c_str());

        // the gnuplot commands go here
        String commandfilename(filename_prefix);
        commandfilename += String(".cmd");
        ofstream cmdout(commandfilename.c_str());

        // the error bar for the x-axis intercept goes here
        String errorbarfilename(filename_prefix);
        errorbarfilename += String(".err");
        ofstream errout(errorbarfilename.c_str());

        // writing the commands
        cmdout <<
        "set ylabel \"ion count\"\n"
        "set xlabel \"concentration\"\n"
        "set key left Left reverse\n";

        if (!format.empty())
        {
          if (format == "png")
          {
            cmdout <<
            "set terminal png \n"
            "set output \"" << filename_prefix << ".png\"\n";
          }
          else if (format == "eps")
          {
            cmdout <<
            "set terminal postscript eps \n"
            "set output \"" << filename_prefix << ".eps\"\n";
          }

        }
        cmdout <<
        "plot \""  << datafilename << "\"  w points ps 2 pt 1 lt 8 title \"data\" "            // want data on first line of key
                                      ",  " << linreg.getIntercept() << "+" <<  linreg.getSlope() << "*x lt 2 lw 3 title \"linear regression: "
        << linreg.getIntercept() << " + " <<  linreg.getSlope() << " * x\" "
                                                                   ", \""  << datafilename << "\"  w points ps 2 pt 1 lt 8 notitle " // draw data a second time, on top of reg. line
                                                                                              ", \"" << errorbarfilename << "\"  using ($1):(0) w points pt 13 ps 2 lt 1 title \"x-intercept: " << linreg.getXIntercept() << "\" "
                                                                                                                                                                                                                             ", \"" << errorbarfilename << "\"  w xerrorbars lw 3 lt 1 title \"95% interval: [ " << linreg.getLower() << ", " << linreg.getUpper() << " ]\"\n";
        cmdout.close();

        // writing the x-axis intercept error bar
        errout << linreg.getXIntercept() << " 0 " << linreg.getLower() << " " << linreg.getUpper() << endl;
        errout.close();

        // writing the peak data points
        vector<double>::const_iterator cit = conc_vec_begin;
        vector<double>::const_iterator ait = area_vec_begin;
        dataout.precision(writtenDigits<double>(0.0));
        for (; cit != conc_vec_end; ++cit, ++ait)
        {
          dataout << *cit << ' ' << *ait << '\n';
        }
        dataout.close();

      }       // end if (write_gnuplot)

      // write results to XML file
      ofstream results;
      results.open(output_filename.c_str());

      results << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" << endl;
      results << "<results_additiveseries>" << endl;
      results << "\t<slope>" << linreg.getSlope() << "</slope>" << endl;
      results << "\t<intercept>" << linreg.getIntercept() << "</intercept>" << endl;
      results << "\t<x_intercept>" << linreg.getXIntercept() << "</x_intercept>" << endl;
      results << "\t<confidence_lowerlimit>" << linreg.getLower() << "</confidence_lowerlimit>" << endl;
      results << "\t<confidence_upperlimit>" << linreg.getUpper() << "</confidence_upperlimit>" << endl;
      results << "\t<pearson_squared>" << linreg.getRSquared() << "</pearson_squared>" << endl;
      results << "\t<std_residuals>" << linreg.getStandDevRes() << "</std_residuals>" << endl;
      results << "\t<t_statistic>" << linreg.getTValue() << "</t_statistic>" << endl;
      results << "</results_additiveseries>" << endl;

      results.close();
    }
    catch (string & s)
    {
      cout << s <<  endl;
      return 1;
    }

    return 0;
  }