//************************************************
// Author: Federica Lionetto
// Created on: 03/03/2015
//************************************************

/*
CCEAttenuationScan reads all the ROOT files of a given CCE attenuation data taking and shows how the mu and sigma of the charge sharing coefficient eta vary as a function of the attenuation.

The CCE attenuation data taking is identified by the following information:
- <sensor>, that is, the type of sensor (Hans410, ...);
- <date>, that is, the date when the measurement was taken;
- <z>, that is, the position along z;
- <firstAtt>, that is, the first value of the attenuation;
- <lastAtt>, that is, the last value of the attenuation;
- <stepAtt>, that is, the step between two subsequent data acquisitions.

Compile with:

make

Run with:

./CCEAttenuationScan [sensor] [date] [z] [firstAtt] [lastAtt [stepAtt] [additional folder]

For example:

./CCEAttenuationScan Hans410 20141121 176 15.0 25.0 0.5

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 CCEAttenuationScan(char *sensor, char *date, char *z, const Float_t firstAtt, const Float_t lastAtt, const Float_t stepAtt, char *externalPath=0);

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

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

    cout << "CCEAttenuationScan reads all the ROOT files of a given CCE attenuation data taking and shows how the mu and sigma of the charge sharing coefficient eta vary as a function of the attenuation." << endl;

    cout << "The CCE bias attenuation data taking is identified by the following information:" << endl;
    cout << "- <sensor>, that is, the type of sensor (Hans410, ...);" << endl;
    cout << "- <date>, that is, the date when the measurement was taken;" << endl;
    cout << "- <z>, that is, the position along z;" << endl;
    cout << "- <firstAtt>, that is, the first value of the attenuation;" << endl;
    cout << "- <lastAtt>, that is, the last value of the attenuation;" << endl;
    cout << "- <stepAtt>, that is, the step between two subsequent data acquisitions." << endl;

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

    cout << "make" << endl;

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

    cout << "./CCEAttenuationScan [sensor] [date] [z] [firstAtt] [lastAtt] [stepAtt] [additional folder]" << endl;

    cout << "For example:" << endl;

    cout << "./CCEAttenuationScan Hans410 20141121 176 15.0 25.0 0.5" << 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 < 7)
  {
    cout << "**************************************************" << endl;

    cout << "Error! Arguments missing..." << endl;
    cout << "Please use the following format:" << endl;
    cout << "./CCEAttenuationScan [1] [2] [3] [4] [5] [6]" << endl;
    cout << "with:" << endl;
    cout << "[1] = Type of sensor (Hans410, ...);" << endl;
    cout << "[2] = Date;" << endl;
    cout << "[3] = Position along z;" << endl;
    cout << "[4] = First value of the attenuation;" << endl;
    cout << "[5] = Last value of the attenuation" << endl;
    cout << "[6] = Step between two subsequent data acquisitions;" << endl;
    cout << "[7] = Additional folder, optional." << endl;
    cout << "Type ./CCEAttenuationScan --info for more information." << endl;
    
    cout << "**************************************************" << endl;

    return 0;
  }
  else
  {
    cout << "Type of sensor: " << argv[1] << endl;
    cout << "Date: " << argv[2] << endl;
    cout << "Position along z: " << argv[3] << endl;
    cout << "First value of the attenuation: " << argv[4] << endl;
    cout << "Last value of the attenuation: " << argv[5] << endl;
    cout << "Step between two subsequent data acquisitions: " << argv[6] << endl;
    if (argc == 7)
      CCEAttenuationScan(argv[1],argv[2],argv[3],atof(argv[4]),atof(argv[5]),atof(argv[6]));
    else if (argc == 8)
      CCEAttenuationScan(argv[1],argv[2],argv[3],atof(argv[4]),atof(argv[5]),atof(argv[6]),argv[7]);
    else
    {
      cout << "Error! Too many arguments given..." << endl;
      
      return 0;
    }
    
    return 0;  
  }
}

void CCEAttenuationScan(char *sensor, char *date, char *z, const Float_t firstAtt, const Float_t lastAtt, const Float_t stepAtt, char *externalPath)
{
  cout << "**************************************************" << endl;
  cout << "Attenuation scan of charge sharing coefficient..." << 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)+"/CCEAttenuationScan";
  string outputDirectory = "/disk/groups/hep/flionett/TestStand/AnalysisResults/"+string(sensor)+"/CCEAttenuationScan";
  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/"+"CCE-ProcessRawData-"+date+"-216-"+z+"z" << 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/"+"CCE-ProcessRawData-"+date+"-216-"+z+"z";
  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);

  char char_input_ROOT[200];
  string input_ROOT;
  string output_ROOT;

  const Int_t steps = (Int_t)((lastAtt-firstAtt)/stepAtt+1);

  Float_t att[steps];
  Float_t uatt[steps];

  Float_t muEtaSignalOverNoise[steps];
  Float_t sigmaEtaSignalOverNoise[steps];

  Float_t umuEtaSignalOverNoise[steps];
  Float_t usigmaEtaSignalOverNoise[steps];

  // Get information from tree.
  Float_t muEtaSignalOverNoise1;
  Float_t sigmaEtaSignalOverNoise1;

  Float_t umuEtaSignalOverNoise1;
  Float_t usigmaEtaSignalOverNoise1;

  TBranch *b_muEtaSignalOverNoise1 = 0;
  TBranch *b_sigmaEtaSignalOverNoise1 = 0;

  TBranch *b_umuEtaSignalOverNoise1 = 0;
  TBranch *b_usigmaEtaSignalOverNoise1 = 0;

  // Open output ROOT file.
  output_ROOT = outputDirectory+"/CCEAttenuationScan-"+date+"-216-"+z+"z"+".root";
  TFile *output = TFile::Open(TString(output_ROOT),"RECREATE");

  for (Int_t step=0;step<steps;step++) {
    att[step] = firstAtt+(Float_t)step*stepAtt;
    uatt[step] = 0.;

    // 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/CCE-ProcessRawData-%s-%.1fdB-216-%sz.root",inputDirectory.c_str(),date,att[step],z);
    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;
    }

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

    // Get information from tree.
    TTree *tFitResults = (TTree *)input->Get("tFitResults");
    int Events = tFitResults->GetEntries();
    if (Events != 1)
    {
      cout << "Error! The ROOT file has been corrupted..." << endl;
      
      return ;
    }
    else 
    {
      tFitResults->SetBranchAddress("muEtaSignalOverNoise",&muEtaSignalOverNoise1,&b_muEtaSignalOverNoise1);
      tFitResults->SetBranchAddress("sigmaEtaSignalOverNoise",&sigmaEtaSignalOverNoise1,&b_sigmaEtaSignalOverNoise1);
      tFitResults->SetBranchAddress("umuEtaSignalOverNoise",&umuEtaSignalOverNoise1,&b_umuEtaSignalOverNoise1);
      tFitResults->SetBranchAddress("usigmaEtaSignalOverNoise",&usigmaEtaSignalOverNoise1,&b_usigmaEtaSignalOverNoise1);

      tFitResults->GetEntry();
    }

    muEtaSignalOverNoise[step] = muEtaSignalOverNoise1;
    sigmaEtaSignalOverNoise[step] = sigmaEtaSignalOverNoise1;
    umuEtaSignalOverNoise[step] = umuEtaSignalOverNoise1;
    usigmaEtaSignalOverNoise[step] = usigmaEtaSignalOverNoise1;

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

  output->cd();

  // Plot mu.
  TGraphErrors *gMuEtaSignalOverNoiseVSAtt = new TGraphErrors(steps,att,muEtaSignalOverNoise,uatt,umuEtaSignalOverNoise);
  InitGraphErrors(gMuEtaSignalOverNoiseVSAtt,"Charge sharing coefficient - #mu","attenuation (dB)","#mu (#mum)");

  TCanvas *cMuEtaSignalOverNoiseVSAtt = new TCanvas(Form("cMuEtaSignalOverNoiseVSAtt-%s",date),"",550,300);
  DrawGraphErrors(cMuEtaSignalOverNoiseVSAtt,gMuEtaSignalOverNoiseVSAtt,"AP",path_to_figures);

  // Plot sigma.
  TGraphErrors *gSigmaEtaSignalOverNoiseVSAtt = new TGraphErrors(steps,att,sigmaEtaSignalOverNoise,uatt,usigmaEtaSignalOverNoise);
  InitGraphErrors(gSigmaEtaSignalOverNoiseVSAtt,"Charge sharing coefficient - #sigma","attenuation (dB)","#sigma (#mum)");

  TCanvas *cSigmaEtaSignalOverNoiseVSAtt = new TCanvas(Form("cSigmaEtaSignalOverNoiseVSAtt-%s",date),"",550,300);
  DrawGraphErrors(cSigmaEtaSignalOverNoiseVSAtt,gSigmaEtaSignalOverNoiseVSAtt,"AP",path_to_figures);

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

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

  return;
}
