//************************************************
// Author: Federica Lionetto
// Created on: 21/07/2014
//************************************************

/*
AttenuationScan reads all the ROOT files of a given attenuation scan data taking, call 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 attenuation;
- 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 attenuation.

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

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

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

void AttenuationScan(char *sensor, char *filename, const Float_t mindB, const Float_t maxdB, char *externalPath = 0);

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

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

    cout << "AttenuationScan reads all the ROOT files of a given attenuation scan data taking, call FindStrip to find the Beetle channel corresponding to the strip hit by the laser, and creates a ROOT file with the following information:" << endl;
    cout << "- a graph with the mean ADC count on the strip hit by the laser as a function of the attenuation;" << endl;
    cout << "- 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 attenuation." << endl;

    cout << "The attenuation scan data taking is identified by the following information:" << endl;
    cout << "- <sensor>, that is, the type of sensor (Hans410, ...);" << endl;
    cout << "- <filename>, that is, the filename excluding the attenuation value and the run type;" << endl;
    cout << "- <mindB>, that is, the lower attenuation value;" << endl;
    cout << "- <maxdB>, that is, the higher attenuation value." << endl;
    
    cout << "**************************************************" << endl;

    return 0;
  }
  else if (argc < 5)
  {
    cout << "**************************************************" << endl;

    cout << "Error! Parameters missing..." << endl;
    cout << "Please use the following format:" << endl;
    cout << "./AttenuationScan [1] [2] [3] [4] [5]" << endl;
    cout << "with:" << endl;
    cout << "[1] = Type of sensor (Hans410, ...);" << endl;
    cout << "[2] = Filename, excluding the attenuation value and the run type;" << endl;
    cout << "[3] = Lower attenuation value;" << endl;
    cout << "[4] = Higher attenuation value;" << endl;
    cout << "[5] = Additional folder, optional." << endl;
    cout << "Type ./AttenuationScan --info for more information." << endl;
    
    cout << "**************************************************" << endl;

    return 0;
  }
  else
  {
    cout << "Type of sensor: " << argv[1] << endl;
    cout << "Filename: " << argv[2] << endl;
    cout << "Lower attenuation value:" << argv[3] << endl;
    cout << "Higher attenuation value: " << argv[4] << endl;
    if (argc == 5)
      AttenuationScan(argv[1],argv[2],atof(argv[3]),atof(argv[4]));
    else if (argc == 6)
      AttenuationScan(argv[1],argv[2],atof(argv[3]),atof(argv[4]),argv[5]);
    else
    {
      cout << "Error! Too many arguments given..." << endl;
      
      return 0;
    }
    
    return 0;  
  }
}

void AttenuationScan(char *sensor, char *filename, const Float_t mindB, const Float_t maxdB, char *externalPath)
{
  cout << "**************************************************" << endl;
  cout << "Performing attenuation 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)+"/AttenuationScan";  
  string outputDirectory = "/disk/groups/hep/flionett/TestStand/AnalysisResults/"+string(sensor)+"/AttenuationScan";
  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+(string)"-21.0dB-las.root";
  string outputFindStrip = outputDirectory+"/FindStrip-"+filename+"-21.0dB-las.root";

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

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

  // const Float_t mindB = 15.0;
  // const Float_t maxdB = 21.0;
  const Float_t stepdB = 0.5;
  const Int_t steps = (Int_t)((maxdB-mindB)/stepdB+1);
  Float_t dB[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++) {
    dB[step] = mindB+step*stepdB;

    // Open input data ROOT files.
    // I did not find a better way to create a string containing the attenuation.
    sprintf(char_input_ROOT,"%s/%s-%.1fdB-las.root",inputDirectory.c_str(),filename,dB[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();

    // 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 *gattenuationScan = new TGraph(steps,dB,meanADC);
  InitGraph(gattenuationScan,"Attenuation scan - 1 strip","Attenuation (dB)","ADC counts");
  TCanvas *cattenuationScan = new TCanvas(Form("cattenuationScan-%s",filename),"",400,300);
  DrawGraph(cattenuationScan,gattenuationScan,"APC",path_to_figures);
  // DrawGraph(cattenuationScan,gattenuationScan,"APC",path_to_figures);

  // Four adjacent strips.
  TGraph *gattenuationScan4 = new TGraph(steps,dB,mean4ADC);
  InitGraph(gattenuationScan4,"Attenuation scan - 4 adjacent strips","Attenuation (dB)","ADC counts");
  TCanvas *cattenuationScan4 = new TCanvas(Form("cattenuationScan4-%s",filename),"",400,300);
  DrawGraph(cattenuationScan4,gattenuationScan4,"APC",path_to_figures);
  // DrawGraph(cattenuationScan4,gattenuationScan4,"APC",path_to_figures);

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

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

  return;
}
