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

/*
LaserDelayScan reads a text file (containing the laser delay in ns and the average ADC signal in ADC counts) and creates a ROOT file with the following information:
- average ADC signal as a function of the laser delay, fit with a Gaussian function.

Compile with:

make

Run with:

./LaserDelayScan [input text file] [additional folder]

where

- [input text file] is the complete path, including the folder and the filename, of the text file one wants to process;
- [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 LaserDelayScan(char *filename, 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 < 2)
  {
    cout << "**************************************************" << endl;
    
    cout << "Error! Input file missing..." << endl;
    cout << "Please use the following format:" << endl;
    cout << "./LaserDelayScan [1] [2]" << endl;
    cout << "with:" << endl;
    cout << "[1] = Input text file, complete path;" << endl;
    cout << "[2] = Additional folder, optional." << endl;
    cout << "Type ./LaserDelayScan --info for more information." << endl;

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

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

void LaserDelayScan(char *filename, char *externalPath)
{
  cout << "**************************************************" << endl;
  cout << "Working on the laser delay scan..." << endl;
  cout << "**************************************************" << endl;

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

  string filename_as_string = string(filename);
  // Check that the filename provided corresponds to a text file.
  int found = filename_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 file.
  int rows = 0;

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

  // Read the text file.
  // Remember that the first two rows must be skipped.  
  float delay;
  float signal;

  vector<float> vdelay;
  vector<float> vsignal;
  vector<float> vdelayErr;
  vector<float> vsignalErr;

  Int_t i = 0;

  // Save information.
  datFile.open(filename_as_string.c_str());
  if (datFile.is_open()) {
    i = 0;
    while (getline(datFile,line)) {
      if (i>1) {
	// cout << line << endl;
	istringstream iss(line);
	iss >> delay >> signal;
	vdelay.push_back(delay);
	vsignal.push_back(signal);
	vdelayErr.push_back(0.);
	vsignalErr.push_back(5.);
      }
      i++;
    }
    datFile.close();
  }
  else
  {
    cout << "Unable to open file." << endl;
    return;
  }

  float *adelay = &vdelay[0];
  float *asignal = &vsignal[0];
  float *adelayErr = &vdelayErr[0];
  float *asignalErr = &vsignalErr[0];

  /*
  cout << adelay[0] << endl;
  cout << adelay[1] << endl;
  cout << asignal[0] << endl;
  cout << asignal[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 = filename_as_string.substr(filename_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"+"/LaserDelayScan";
  system(path_to_make_figures.c_str());
  path_to_make_figures = "mkdir "+analysis+"/Figures"+"/LaserDelayScan"+"/"+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+"/LaserDelayScan-"+TString(filename_as_string_no_path_no_extension)+".root","RECREATE"); 

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

  int rowsData = rows-2;

  TGraphErrors *glaserDelayScan = new TGraphErrors(rowsData,adelay,asignal,adelayErr,asignalErr);

  // Fit with a polynomial function of degree 2 and get the delay and the signal at the peak.
  // gStyle->SetOptFit(0011);
  float minFit = 47.;
  float maxFit = 75.;
  TF1 *fpol2 = new TF1("fpol2","pol2",minFit,maxFit);
  glaserDelayScan->Fit("fpol2","R");

  float delayPeak = -1*(fpol2->GetParameter(1))/(2*fpol2->GetParameter(2));
  float signalPeak = fpol2->Eval(delayPeak);

  cout << "Delay at the peak: " << delayPeak << endl;
  cout << "Signal at the peak: " << signalPeak << endl;

  InitGraphErrors(glaserDelayScan,"Laser delay scan","Delay (ns)","Average ADC signal");
  DrawGraphErrors(claserDelayScan,glaserDelayScan,"AP",path_to_figures);

  output->Close();

  return;
}
