//************************************************
// Author: Federica Lionetto
// Created on: 20/11/2014
//************************************************

/*
IVScan reads two text files (containing the bias voltage and the current values) and creates a ROOT file with the following information:
- current as a function of the bias voltage.

Compile with:

make

Run with:

./IVScan [input text file 1] [input text file 2] [additional folder]

where

- [input text file 1] is the complete path, including the folder and the filename, of the text file one wants to process (increasing bias voltage);
- [input text file 2] is the complete path, including the folder and the filename, of the text file one wants to process (decreasing bias voltage);
- [additional folder] is the optional additional folder where the output will be saved.

A folder named AnalysisResults will be created in a fixed location and a ROOT file will be saved in there. A folder named Figures will be created inside the folder named AnalysisResults, with some monitoring plots.

If needed, an additional folder can be specified, that will be created inside the folder named AnalysisResults.
*/

#include "../Tools/Lib.C"
#include "../Tools/lhcbStyle.C"
#include "../Tools/Style.C"

#include "../Tools/Par.C"

void IVScan(char *filename1, char *filename2, char *externalPath=0);

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

  if ((argc ==2) && (string(argv[1]) == "--info"))
  {
    cout << "**************************************************" << endl;

    cout << "IVScan reads two text files (containing the bias voltage and the current values) and creates a ROOT file with the following information:" << endl;
    cout << "- current as a function of the bias voltage." << endl;

    cout << "Compile with:" << endl;

    cout << "make" << endl;

    cout << "Run with:" << endl;

    cout << "./IVScan [input text file 1] [input text file 2] [additional folder]" << endl;

    cout << "where" << endl;

    cout << "- [input text file 1] is the complete path, including the folder and the filename, of the text file one wants to process (increasing bias voltage);" << endl;
    cout << "- [input text file 2] is the complete path, including the folder and the filename, of the text file one wants to process (decreasing bias voltage);" << endl;
    cout << "- [additional folder] is the optional additional folder where the output will be saved." << endl;

    cout << "A folder named AnalysisResults will be created in a fixed location and a ROOT file will be saved in there. A folder named Figures will be created inside the folder named AnalysisResults, with some monitoring plots." << endl;

    cout << "If needed, an additional folder can be specified, that will be created inside the folder named AnalysisResults." << endl;
    
    cout << "**************************************************" << endl;

    return 0;
  }
  else if (argc < 3)
  {
    cout << "**************************************************" << endl;
    
    cout << "Error! Input files missing..." << endl;
    cout << "Please use the following format:" << endl;
    cout << "./IVScan [1] [2] [3]" << endl;
    cout << "with:" << endl;
    cout << "[1] = Input text file 1, complete path (increasing bias voltage);" << endl;
    cout << "[2] = Input text file 2, complete path (decreasing bias voltage);" << endl;
    cout << "[3] = Additional folder, optional." << endl;
    cout << "Type ./IVScan --info for more information." << endl;

    cout << "**************************************************" << endl;

    return 0;  
  }
  else
  {
    cout << "File 1 to process: " << argv[1] << endl;
    cout << "File 2 to process: " << argv[2] << endl;
    if (argc == 3)
      IVScan(argv[1],argv[2]);
    else if (argc == 4)
      IVScan(argv[1],argv[2],argv[3]);
    else
    {
      cout << "Error! Too many arguments given..." << endl;
      
      return 0;
    }
    
    return 0;  
  }  
}

void IVScan(char *filename1, char *filename2, char *externalPath)
{
  cout << "**************************************************" << endl;
  cout << "Working on the IV scan..." << endl;
  cout << "**************************************************" << endl;

  // Do not comment this line.
  gROOT->ProcessLine("#include <vector>");

  int found;

  string filename1_as_string = string(filename1);
  // Check that the filename provided corresponds to a text file.
  found = filename1_as_string.find(".dat");
  if (found==string::npos)  {
    cout << "Error! The filename provided is not associated to a text file." << endl;
    return;
  }

  string filename2_as_string = string(filename2);
  // Check that the filename provided corresponds to a text file.
  found = filename2_as_string.find(".dat");
  if (found==string::npos)  {
    cout << "Error! The filename provided is not associated to a text file." << endl;
    return;
  }

  // Open input text file.
  ifstream datFile;
  std::string line;

  // Number of rows to be read from the text files.
  int rows1;
  int rows2;

  // Open file 1.
  // Determine number of rows to be read from the text file.
  datFile.open(filename1_as_string.c_str());
  if (datFile.is_open()) {
    rows1 = 0;
    while (getline(datFile,line))
      rows1++;
    cout << "Number of rows in the input text file 1: " << rows1 << endl;
    datFile.close();
  }
  else 
  {
    cout << "Unable to open file." << endl;
    return;
  }

  // Open file 2.
  // Determine number of rows to be read from the text file.
  datFile.open(filename2_as_string.c_str());
  if (datFile.is_open()) {
    rows2 = 0;
    while (getline(datFile,line))
      rows2++;
    cout << "Number of rows in the input text file 2: " << rows2 << endl;
    datFile.close();
  }
  else 
  {
    cout << "Unable to open file." << endl;
    return;
  }

  // Read the text file.
  // Remember that the first row must be skipped.  
  float V;
  float I;
  float IErr;

  Int_t i;

  // Read text file 1.
  vector<float> vV1;
  vector<float> vI1;
  vector<float> vVErr1;
  vector<float> vIErr1;

  // Save information.
  datFile.open(filename1_as_string.c_str());
  if (datFile.is_open()) {
    i = 0;
    while (getline(datFile,line)) {
      if (i>0) {
	// cout << line << endl;
	istringstream iss(line);
	iss >> V >> I >> IErr;
	vV1.push_back(V);
	vI1.push_back(I);
	vVErr1.push_back(0.);
	vIErr1.push_back(IErr);
      }
      i++;
    }
    datFile.close();
  }
  else
  {
    cout << "Unable to open file." << endl;
    return;
  }

  float *aV1 = &vV1[0];
  float *aI1 = &vI1[0];
  float *aVErr1 = &vVErr1[0];
  float *aIErr1 = &vIErr1[0];
 
  /*
  cout << aV1[0] << endl;
  cout << aV1[1] << endl;
  cout << aI1[0] << endl;
  cout << aI1[1] << endl;
  cout << aVErr1[0] << endl;
  cout << aVErr1[1] << endl;
  cout << aIErr1[0] << endl;
  cout << aIErr1[1] << endl;
  */

  // Read text file 2.
  vector<float> vV2;
  vector<float> vI2;
  vector<float> vVErr2;
  vector<float> vIErr2;

  // Save information.
  datFile.open(filename2_as_string.c_str());
  if (datFile.is_open()) {
    i = 0;
    while (getline(datFile,line)) {
      if (i>0) {
	// cout << line << endl;
	istringstream iss(line);
	iss >> V >> I >> IErr;
	vV2.push_back(V);
	vI2.push_back(I);
	vVErr2.push_back(0.);
	vIErr2.push_back(IErr);
      }
      i++;
    }
    datFile.close();
  }
  else
  {
    cout << "Unable to open file." << endl;
    return;
  }

  float *aV2 = &vV2[0];
  float *aI2 = &vI2[0];
  float *aVErr2 = &vVErr2[0];
  float *aIErr2 = &vIErr2[0];

  /* 
  cout << aV2[0] << endl;
  cout << aV2[1] << endl;
  cout << aI2[0] << endl;
  cout << aI2[1] << endl;
  cout << aVErr2[0] << endl;
  cout << aVErr2[1] << endl;
  cout << aIErr2[0] << endl;
  cout << aIErr2[1] << endl;
  */

  // Do some fanciness to get the directory right.
  string analysis = "/disk/groups/hep/flionett/TestStand/AnalysisResults";
  if (externalPath!=0)
    analysis = string(analysis+"/"+externalPath);

  string filename_as_string_no_path = filename1_as_string.substr(filename1_as_string.find_last_of('/')+1);
  string filename_as_string_no_path_no_extension = filename_as_string_no_path.substr(0,filename_as_string_no_path.length()-4);

  // Create a folder named AnalysisResults. Do not worry, nothing bad is going to happen if the folder already exists.
  string path_to_make = "mkdir -p "+analysis;
  system(path_to_make.c_str());
  cout << "Setting output to: " << path_to_make << endl;

  // Create a folder named Figures inside the folder named AnalysisResults.
  string path_to_make_figures = "mkdir "+analysis+"/Figures";
  system(path_to_make_figures.c_str());
  path_to_make_figures = "mkdir "+analysis+"/Figures"+"/IVScan";
  system(path_to_make_figures.c_str());
  path_to_make_figures = "mkdir "+analysis+"/Figures"+"/IVScan"+"/"+filename_as_string_no_path_no_extension;
  system(path_to_make_figures.c_str());
  cout << "Setting figures to: " << path_to_make_figures << endl;  

  TString path_to_figures = (string(path_to_make_figures)).substr((string(path_to_make_figures)).find_last_of(' ')+1);

  // Open output ROOT file.
  TFile *output = TFile::Open(analysis+"/IVScan-"+TString(filename_as_string_no_path_no_extension)+".root","RECREATE"); 

  TCanvas *cIVScan = new TCanvas("cIVScan","",400,300);

  int rowsData1 = rows1-1;
  int rowsData2 = rows2-1;

  TMultiGraph *mgIVScan = new TMultiGraph();

  TGraphErrors *gIVScan1 = new TGraphErrors(rowsData1,aV1,aI1,aVErr1,aIErr1);
  TGraphErrors *gIVScan2 = new TGraphErrors(rowsData2,aV2,aI2,aVErr2,aIErr2);

  InitGraphErrors(gIVScan1,"IV scan","Bias voltage (V)","Current (#muA)");
  InitGraphErrors(gIVScan2,"IV scan","Bias voltage (V)","Current (#muA)");

  gIVScan1->SetMarkerColor(kMagenta);
  gIVScan2->SetMarkerColor(kOrange);

  TLegend *legIVScan = CreateLegend2(gIVScan1,"increasing V",gIVScan2,"decreasing V","epw",0.2,0.6,0.5,0.9);
  // TLegend *legIVScan = CreateLegend2(gIVScan1,"18/03/2015",gIVScan2,"22/07/2014","epw",0.65,0.18,0.94,0.42);

  mgIVScan->Add(gIVScan1);
  mgIVScan->Add(gIVScan2);

  DrawGraphCompare(cIVScan,mgIVScan,legIVScan,"IV scan","Bias voltage (V)","Current (#muA)","APE",path_to_figures);

  output->Close();

  return;
}
