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

/*
BiasVoltageScan reads all the ROOT files of a given bias voltage scan data taking, calls FindStrip to find the Beetle channel corresponding to the strip hit by the laser, and creates a ROOT file with the following information:
- a graph with the mean ADC count on the strip hit by the laser as a function of the bias voltage;
- a graph with the mean of the sum of the ADC counts of four adjacent strips around that hit by the laser as a function of the bias voltage.

The bias voltage scan data taking is identified by the following information:
- <sensor>, that is, the type of sensor (Hans410, ...);
- <filename>, that is, the filename excluding the bias voltage value and the run type.
*/

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

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

void BiasVoltageScan(char *sensor, 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 < 3)
  {
    cout << "**************************************************" << endl;

    cout << "Error! Type of sensor or filename missing..." << endl;
    cout << "Please use the following format:" << endl;
    cout << "./BiasVoltageScan [1] [2] [3]" << endl;
    cout << "with:" << endl;
    cout << "[1] = Type of sensor (Hans410, ...);" << endl;
    cout << "[2] = Filename, excluding the bias voltage value and the run type;" << endl;
    cout << "[3] = Additional folder, optional." << endl;
    cout << "Type ./BiasVoltageScan --info for more information." << endl;
    
    cout << "**************************************************" << endl;

    return 0;
  }
  else
  {
    cout << "Type of sensor: " << argv[1] << endl;
    cout << "Filename: " << argv[2] << endl;
    if (argc == 3)
      BiasVoltageScan(argv[1],argv[2]);
    else if (argc == 4)
      BiasVoltageScan(argv[1],argv[2],argv[3]);
    else
    {
      cout << "Error! Too many arguments given..." << endl;
      
      return 0;
    }
    
    return 0;  
  }
}

void BiasVoltageScan(char *sensor, char *filename, char *externalPath)
{
  cout << "**************************************************" << endl;
  cout << "Performing bias voltage scan..." << endl;
  cout << "**************************************************" << endl;

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

  // Do some fanciness to get the directory right.
  string inputDirectory = "/disk/groups/hep/flionett/TestStand/AnalysisResults/"+string(sensor)+"/BiasVoltageScan";  
  string outputDirectory = "/disk/groups/hep/flionett/TestStand/AnalysisResults/"+string(sensor)+"/BiasVoltageScan";
  if (externalPath!=0)
    outputDirectory = string(outputDirectory+"/"+externalPath);
  cout << "The input directory is: " << inputDirectory << endl;
  cout << "The output directory is: " << outputDirectory << endl;

  // Create the outputDirectory directory if it does not exist.
  string path_to_make = "mkdir -p "+outputDirectory;
  system(path_to_make.c_str());

  cout << "Figures stored in: " << outputDirectory+"/Figures/"+filename << endl;

  // Create a directory named Figures inside the directory named outputDirectory if it does not exist.
  string path_to_make_figures = "mkdir -p "+outputDirectory+"/Figures/"+filename;
  system(path_to_make_figures.c_str());

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

  // Execute findStrip.
  int strip;
  string direction;

  string inputFindStrip = inputDirectory+"/"+filename+"-150V-las.root";
  string outputFindStrip = outputDirectory+"/FindStrip-"+filename+"-150V-las.root";

  FindStrip(inputFindStrip,outputFindStrip,path_to_figures,&strip,&direction);  

  char char_input_ROOT[200];
  string input_ROOT;
  string output_ROOT = outputDirectory+"/BiasVoltageScan-"+filename+".root";

  const Float_t minV = 30.;
  const Float_t maxV = 350.;
  const Float_t stepV = 10.;
  const Int_t steps = (Int_t)((maxV-minV)/stepV+1);
  Float_t V[steps];
  Float_t meanADC[steps];
  Float_t mean4ADC[steps];

  // Open output ROOT file.
  TFile *output = TFile::Open(TString(output_ROOT),"RECREATE");

  for (Int_t step=0;step<steps;step++) {
    V[step] = minV+step*stepV;

    // Open input data ROOT files.
    // I did not find a better way to create a string containing the bias voltage.
    sprintf(char_input_ROOT,"%s/%s-%dV-las.root",inputDirectory.c_str(),filename,(int)V[step]);
    input_ROOT = string(char_input_ROOT);
    // Check that the filename provided corresponds to a ROOT file.
    int found = input_ROOT.find(".root");
    if (found==string::npos)  {
      cout << "Error! The filename provided is not associated to a ROOT file." << endl;
      return;
    }
    // Check that the filename provided corresponds to an existing ROOT file.
    /*
      if (!(boost::filesystem::exists(char_input_ROOT))) {
      cout << "Error! The filename provided is not associated to an existing ROOT file." << endl;
      return;
      }
    */

    cout << "Open ROOT file #" << step+1 << ": " << input_ROOT << endl;
    TFile *input = TFile::Open(TString(input_ROOT));

    // Only one strip.
    TH1D *hist = (TH1D *)input->Get(Form("hADCPedSub%d",strip));
    meanADC[step] = hist->GetMean();

    cout << "Histograms: " << endl;
    cout << Form("hADCPedSub%d",strip) << endl;
    cout << Form("hADCPedSub%d",strip+NSkip) << endl;
    cout << Form("hADCPedSub%d",strip-NSkip) << endl;
    cout << Form("hADCPedSub%d",strip-2*NSkip) << endl;
    cout << Form("hADCPedSub%d",strip+2*NSkip) << endl;

    // Four adjacent strips.
    TH1D *hist1 = (TH1D *)input->Get(Form("hADCPedSub%d",strip));
    TH1D *hist2 = (TH1D *)input->Get(Form("hADCPedSub%d",strip+NSkip));
    TH1D *hist3 = (TH1D *)input->Get(Form("hADCPedSub%d",strip-NSkip));
    TH1D *hist4;
    if (direction == "left")
      hist4 = (TH1D *)input->Get(Form("hADCPedSub%d",strip-2*NSkip));
    else if (direction == "right")
      hist4 = (TH1D *)input->Get(Form("hADCPedSub%d",strip+2*NSkip));
    mean4ADC[step] = hist1->GetMean()+hist2->GetMean()+hist3->GetMean()+hist4->GetMean();

    // Close input data ROOT files.
    input->Close();
  }

  output->cd();

  // Only one strip.
  TGraph *gbiasVoltageScan = new TGraph(steps,V,meanADC);
  InitGraph(gbiasVoltageScan,"Bias voltage scan - 1 strip","Bias voltage (V)","ADC counts");
  TCanvas *cbiasVoltageScan = new TCanvas(Form("cbiasVoltageScan-%s",filename),"",400,300);
  DrawGraph(cbiasVoltageScan,gbiasVoltageScan,"APC",path_to_figures);

  // Four adjacent strips.
  TGraph *gbiasVoltageScan4 = new TGraph(steps,V,mean4ADC);
  InitGraph(gbiasVoltageScan4,"Bias voltage scan - 4 adjacent strips","Bias voltage (V)","ADC counts");
  TCanvas *cbiasVoltageScan4 = new TCanvas(Form("cbiasVoltageScan4-%s",filename),"",400,300);
  DrawGraph(cbiasVoltageScan4,gbiasVoltageScan4,"APC",path_to_figures);

  // Write output ROOT file.
  output->Write();

  // Close output ROOT file.
  output->Close();

  return;
}
