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

/*
PulseShapevsV reads two text files (containing the bias voltage and the current values) and creates a ROOT file with the following information:
- laser delay at the peak of the Beetle pulse shape (float laserDelayAtPeak) as a function of the bias voltage;
- average ADC signal at the peak of the Beetle pulse shape (float averageADCSignalAtPeak) as a function of the bias voltage.

Compile with:

make

Run with:

./PulseShapevsV [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 PulseShapevsV(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 << "Some comments." << 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 << "./PulseShapevsV [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 ./PulseShapevsV --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)
      PulseShapevsV(argv[1],argv[2]);
    else if (argc == 4)
      PulseShapevsV(argv[1],argv[2],argv[3]);
    else
    {
      cout << "Error! Too many arguments given..." << endl;
      
      return 0;
    }
    
    return 0;  
  }  
}

void PulseShapevsV(char *filename1, char *filename2, char *externalPath)
{
  cout << "**************************************************" << endl;
  cout << "Showing the pulse shape changes as a function of the bias voltage..." << 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 trash2;
  float trash3;
  float laserDelayAtPeak;
  float averageADCSignalAtPeak;

  Int_t i;

  // Read text file 1.
  vector<float> vV1;
  vector<float> vlaserDelayAtPeak1;
  vector<float> vaverageADCSignalAtPeak1;

  // 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 >> trash2 >> trash3 >> laserDelayAtPeak >> averageADCSignalAtPeak;
	vV1.push_back(V);
	vlaserDelayAtPeak1.push_back(laserDelayAtPeak);
	vaverageADCSignalAtPeak1.push_back(averageADCSignalAtPeak);
      }
      i++;
    }
    datFile.close();
  }
  else
  {
    cout << "Unable to open file." << endl;
    return;
  }

  float *aV1 = &vV1[0];
  float *alaserDelayAtPeak1 = &vlaserDelayAtPeak1[0];
  float *aaverageADCSignalAtPeak1 = &vaverageADCSignalAtPeak1[0];
 
  /*
    cout << aV1[0] << endl;
    cout << aV1[1] << endl;
    cout << alaserDelayAtPeak1[0] << endl;
    cout << alaserDelayAtPeak1[1] << endl;
    cout << aaverageADCSignalAtPeak1[0] << endl;
    cout << aaverageADCSignalAtPeak1[1] << endl;
  */

  // Read text file 2.
  vector<float> vV2;
  vector<float> vlaserDelayAtPeak2;
  vector<float> vaverageADCSignalAtPeak2;

  // 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 >> trash2 >> trash3 >> laserDelayAtPeak >> averageADCSignalAtPeak;
	vV2.push_back(V);
	vlaserDelayAtPeak2.push_back(laserDelayAtPeak);
	vaverageADCSignalAtPeak2.push_back(averageADCSignalAtPeak);
      }
      i++;
    }
    datFile.close();
  }
  else
  {
    cout << "Unable to open file." << endl;
    return;
  }

  float *aV2 = &vV2[0];
  float *alaserDelayAtPeak2 = &vlaserDelayAtPeak2[0];
  float *aaverageADCSignalAtPeak2 = &vaverageADCSignalAtPeak2[0];
 
  /*
    cout << aV2[0] << endl;
    cout << aV2[1] << endl;
    cout << alaserDelayAtPeak2[0] << endl;
    cout << alaserDelayAtPeak2[1] << endl;
    cout << aaverageADCSignalAtPeak2[0] << endl;
    cout << aaverageADCSignalAtPeak2[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()-18);

  // 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"+"/PulseShapevsV";
  system(path_to_make_figures.c_str());
  path_to_make_figures = "mkdir "+analysis+"/Figures"+"/PulseShapevsV"+"/"+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+"/PulseShapevsV-"+TString(filename_as_string_no_path_no_extension)+".root","RECREATE"); 

  TCanvas *claserDelayAtPeakvsV = new TCanvas("cLaserDelayAtPeakvsV","",400,300);
  TCanvas *caverageADCSignalAtPeakvsV = new TCanvas("caverageADCSignalAtPeakvsV","",400,300); 

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

  TMultiGraph *mglaserDelayAtPeakvsV = new TMultiGraph();
  TMultiGraph *mgaverageADCSignalAtPeakvsV = new TMultiGraph();

  TGraph *glaserDelayAtPeakvsV1 = new TGraph(rowsData1,aV1,alaserDelayAtPeak1);
  TGraph *glaserDelayAtPeakvsV2 = new TGraph(rowsData2,aV2,alaserDelayAtPeak2);

  TGraph *gaverageADCSignalAtPeakvsV1 = new TGraph(rowsData1,aV1,aaverageADCSignalAtPeak1);
  TGraph *gaverageADCSignalAtPeakvsV2 = new TGraph(rowsData2,aV2,aaverageADCSignalAtPeak2);

  InitGraph(glaserDelayAtPeakvsV1,"Laser delay","Bias voltage (V)","Laser delay (ns)");
  InitGraph(glaserDelayAtPeakvsV2,"Laser delay","Bias voltage (V)","Laser delay (ns)");

  InitGraph(gaverageADCSignalAtPeakvsV1,"Average ADC signal","Bias voltage (V)","<ADC signal> (ADC counts)");
  InitGraph(gaverageADCSignalAtPeakvsV2,"Average ADC signal","Bias voltage (V)","<ADC signal> (ADC counts)");

  glaserDelayAtPeakvsV1->SetMarkerColor(kMagenta);
  glaserDelayAtPeakvsV2->SetMarkerColor(kOrange);

  gaverageADCSignalAtPeakvsV1->SetMarkerColor(kMagenta);
  gaverageADCSignalAtPeakvsV2->SetMarkerColor(kOrange);

  TLegend *leglaserDelayAtPeakvsV = CreateLegend2(glaserDelayAtPeakvsV1,"increasing V",glaserDelayAtPeakvsV2,"decreasing V","pw");

  TLegend *legaverageADCSignalAtPeakvsV = CreateLegend2(gaverageADCSignalAtPeakvsV1,"increasing V",gaverageADCSignalAtPeakvsV2,"decreasing V","pw",0.45,0.25,0.90,0.50);

  mglaserDelayAtPeakvsV->Add(glaserDelayAtPeakvsV1);
  mglaserDelayAtPeakvsV->Add(glaserDelayAtPeakvsV2);

  mgaverageADCSignalAtPeakvsV->Add(gaverageADCSignalAtPeakvsV1);
  mgaverageADCSignalAtPeakvsV->Add(gaverageADCSignalAtPeakvsV2);

  DrawGraphCompare(claserDelayAtPeakvsV,mglaserDelayAtPeakvsV,leglaserDelayAtPeakvsV,"Laser delay","Bias voltage (V)","Laser delay (ns)","APE",path_to_figures);

  DrawGraphCompare(caverageADCSignalAtPeakvsV,mgaverageADCSignalAtPeakvsV,legaverageADCSignalAtPeakvsV,"Average ADC signal","Bias voltage (V)","<ADC signal> (ADC counts)","APE",path_to_figures);

  output->Close();

  return;
}
