Esempio n. 1
0
int main(int argc, char** argv)
{
  //Check if all nedeed arguments to parse are there                                                                                                                               
  if(argc != 2)
  {
    std::cerr << ">>>>> analysis.cpp::usage: " << argv[0] << " configFileName" << std::endl ;
    return 1;
  }
  
  
  
  // Parse the config file                                                                                                                                                          
  parseConfigFile (argv[1]) ;
  
  std::string treeName = gConfigParser -> readStringOption("Input::treeName");
  std::string inputFileList = gConfigParser -> readStringOption("Input::inputFileList");
  
  
  
  // Open old tree
  TChain* chain = new TChain(treeName.c_str());
  if(!FillChain(*chain, inputFileList.c_str())) return 1;
  treeReader reader((TTree*)(chain));
  
  
  
  // Open output root file for clone tree
  std::string outputRootFileName = "clone.root";
  TFile outputRootFile(outputRootFileName.c_str(), "RECREATE");
  outputRootFile.cd();

  TTree* cloneTree = chain -> CloneTree(0);
  
  
  
  std::cout << ">>>>> cloneNtple.cpp::Read " << chain -> GetEntries() << " entries" << std::endl;  
  for(int entry = 0 ; entry < chain -> GetEntries() ; ++entry)
  {
    reader.GetEntry(entry);
    if((entry%1000) == 0) std::cout << ">>>>> analysis::GetEntry " << entry << std::endl;   
    
    if( (reader.Get4V("jets")->size()) >= 4 )
      cloneTree -> Fill();
    
  } // loop over the events
  
  
  
  cloneTree -> AutoSave();
  outputRootFile.Close();
  
  return 0;
}
Esempio n. 2
0
int main (int argc, char** argv)
{  
  std::cout<<"--------> DUMPER: READ RECO DATA AND PRODUCE PROFILE PLOTS <--------"<<std::endl;
  
  
  //--------Read Options--------------------------------
  std::string inputFileList(argv[1]);
  std::string outputLabel = argv[2];
  int entriesMax = atoi(argv[3]);
  
  std::cout << "--------------------------------" << std::endl;
  std::cout << "inputFileList: "       << argv[1] << std::endl;
  std::cout << "outputLabel: "         << argv[2] << std::endl;
  std::cout << "entriesMax: "          << argv[3] << std::endl;
  std::cout << "--------------------------------" << std::endl;
  
  
  //-------start to read the input file list--------
  
  TChain* treeReco = new TChain("ntu");
  RecoTreeVars recoTV;
  InitRecoTree(treeReco,recoTV);
  FillChain(treeReco,inputFileList);
  
  
  //---------output histograms----------------
  TFile* outputFile = TFile::Open(Form("plots/plots_studyProfiles_%s.root",outputLabel.c_str()),"RECREATE");
  TH2F* h2_beamPosition_TDC = new TH2F("h2_beamPosition_TDC","",100,-240,-140.,100,-146,-46.);
  TH2F* h2_beamPosition_hodo11 = new TH2F("h2_beamPosition_hodo11","",160,-210.,-130.,160,-155.,-75.);
  TH2F* h2_beamPosition_hodo22 = new TH2F("h2_beamPosition_hodo22","",160,-210.,-130.,160,-155.,-75.);
  TH2F* h2_beamPosition_hodo12 = new TH2F("h2_beamPosition_hodo12","",160,-210.,-130.,160,-155.,-75.);
  TH2F* h2_beamPosition_hodo21 = new TH2F("h2_beamPosition_hodo21","",160,-210.,-130.,160,-155.,-75.);
  
  std::map<int,TProfile*> p_cellProfileX_TDC;
  std::map<int,TProfile*> p_cellProfileX_hodo12;
  std::map<int,TProfile*> p_cellProfileY_TDC;
  std::map<int,TProfile*> p_cellProfileY_hodo12;
  std::map<int,TH1F*> h_cell_charge;
  for(int iCh = 0; iCh < 32; ++iCh)
  {
    p_cellProfileX_TDC[iCh]    = new TProfile(Form("p_cell%02dProfileX_TDC",iCh),"",   100,-240.,-140.);
    p_cellProfileX_hodo12[iCh] = new TProfile(Form("p_cell%02dProfileX_hodo12",iCh),"",160,-210.,-130.);
    p_cellProfileY_TDC[iCh]    = new TProfile(Form("p_cell%02dProfileY_TDC",iCh),"",   100,-146., -46.);
    p_cellProfileY_hodo12[iCh] = new TProfile(Form("p_cell%02dProfileY_hodo12",iCh),"",160,-155., -75.);
    h_cell_charge[iCh] = new TH1F(Form("h_cell%02d_charge",iCh),"",100000,0., 10000000.);
  }
  
  TH1F* h_total_charge = new TH1F("h_total_charge","",100000,0., 10000000.);
  TProfile2D* p2_cellPosition_TDC    = new TProfile2D("p2_cellPosition_TDC",   "",100,-240.,-140.,100,-152.,-52.);
  TProfile2D* p2_cellPosition_hodo12 = new TProfile2D("p2_cellPosition_hodo12","",160,-210.,-130.,160,-155.,-75.);
  
  
  //-----Data loop--------------------------------------------------------
  int nEntries = treeReco -> GetEntries();
  if( entriesMax < 0 ) entriesMax = nEntries;
  for(int iEntry = 0; iEntry < entriesMax; ++iEntry)
  {
    if( iEntry%1 == 0 ) std::cout << ">>> reading entry: " << iEntry << " / " << nEntries << "\r" << std::flush;
    
    
    //---Read the entry
    ClearRecoTreeVars(recoTV);
    treeReco->GetEntry(iEntry);
    
    
    //---Reconstruct beam position
    float beamX_TDC = -recoTV.tableX + recoTV.tdcX;
    float beamY_TDC = -recoTV.tableY + recoTV.tdcY;
    
    float hodoX1 = GetHodoWire(recoTV.nHodoX1,recoTV.hodoX1);
    float hodoY1 = GetHodoWire(recoTV.nHodoY1,recoTV.hodoY1);
    float hodoX2 = GetHodoWire(recoTV.nHodoX2,recoTV.hodoX2);
    float hodoY2 = GetHodoWire(recoTV.nHodoY2,recoTV.hodoY2);
    float beamX_hodo1 = hodoX1 >= 0 ? -recoTV.tableX + 0.5*hodoX1 : -999;
    float beamY_hodo1 = hodoY1 >= 0 ? -recoTV.tableY - 0.5*hodoY1 : -999;
    float beamX_hodo2 = hodoX2 >= 0 ? -recoTV.tableX + 0.5*hodoX2 : -999;
    float beamY_hodo2 = hodoY2 >= 0 ? -recoTV.tableY - 0.5*hodoY2 : -999;
    
    
    //---Fill histograms
    h2_beamPosition_TDC -> Fill(beamX_TDC,beamY_TDC);
    if( beamX_hodo1 != -999 && beamY_hodo1 != -999 ) h2_beamPosition_hodo11 -> Fill(beamX_hodo1,beamY_hodo1);
    if( beamX_hodo2 != -999 && beamY_hodo2 != -999 ) h2_beamPosition_hodo22 -> Fill(beamX_hodo2,beamY_hodo2);
    if( beamX_hodo1 != -999 && beamY_hodo2 != -999 ) h2_beamPosition_hodo12 -> Fill(beamX_hodo1,beamY_hodo2);
    if( beamX_hodo2 != -999 && beamY_hodo1 != -999 ) h2_beamPosition_hodo21 -> Fill(beamX_hodo2,beamY_hodo1);
    
    float total_charge = 0.;
    for(int iCh = 0; iCh < 32; ++iCh)
    {
      if( recoTV.amp_DQM[iCh] > 500 ) p2_cellPosition_TDC    -> Fill(beamX_TDC,  beamY_TDC,  32*(iCh%2)+pow(-1,iCh)*iCh);
      if( recoTV.amp_DQM[iCh] > 500 ) p2_cellPosition_hodo12 -> Fill(beamX_hodo1,beamY_hodo2,32*(iCh%2)+pow(-1,iCh)*iCh);
      if( recoTV.amp_DQM[iCh] > 0. && recoTV.amp_DQM[iCh] < 999999. )
      {
        p_cellProfileX_TDC[iCh]    -> Fill(beamX_TDC,  recoTV.amp_DQM[iCh]);
        p_cellProfileX_hodo12[iCh] -> Fill(beamX_hodo1,recoTV.amp_DQM[iCh]);
        p_cellProfileY_TDC[iCh]    -> Fill(beamY_TDC,  recoTV.amp_DQM[iCh]);
        p_cellProfileY_hodo12[iCh] -> Fill(beamY_hodo2,recoTV.amp_DQM[iCh]);
        h_cell_charge[iCh] -> Fill(recoTV.charge_DQM[iCh]);
        if(iCh==12 || iCh==13 || iCh==18 || iCh==19)
          total_charge += recoTV.charge_DQM[iCh];
      }
    }
    
    if( (fabs(beamX_hodo1+180.) < 5.) &&
        (fabs(beamY_hodo2+117.) < 5.) )
      h_total_charge -> Fill(total_charge);
  }
  std::cout << std::endl;
  
  
  // //-----close everything-----------------------------------------------------
  outputFile -> Write();
  outputFile -> Close();
  
  
  //---------Done-----------------------------------------------------------------
}
Esempio n. 3
0
void trisCheckStability(Char_t* EBEE = 0,
                        Int_t evtsPerPoint = 0,
                        std::string dayMin = "",
                        std::string dayMax = "",
                        float absEtaMin = -1.,
                        float absEtaMax = -1.)
{
  // Set style options
  gROOT->Reset();
  gROOT->SetStyle("Plain");
  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);
  gStyle->SetOptTitle(0); 
  gStyle->SetOptStat(1110); 
  gStyle->SetOptFit(1); 
  
  
  
  // Check qualifiers
  if ( strcmp(EBEE,"EB")!=0 && strcmp(EBEE,"EE")!=0 )
  {
    std::cout << "CHK-STB Error: unknown partition " << EBEE << std::endl;
    std::cout << "CHK-STB Select either EB or EE ! " << std::endl;
    return;
  }
  
  
  
  // Get trees
  std::cout << std::endl;
  
  TChain* ntu_DA = new TChain("ntu");
  FillChain(ntu_DA,"inputDATA.txt");
  std::cout << "     DATA: " << std::setw(8) << ntu_DA->GetEntries() << " entries" << std::endl;
  
  TChain* ntu_MC = new TChain("ntu");
  FillChain(ntu_MC,"inputMC.txt");
  std::cout << "REFERENCE: " << std::setw(8) << ntu_MC->GetEntries() << " entries" << std::endl;
  
  if (ntu_DA->GetEntries() == 0 || ntu_MC->GetEntries() == 0 )
  {
    std::cout << "CHK-STB Error: At least one file is empty" << std::endl; 
    return;
  }
  
  
  
  // Set branch addresses
  int runId;
  int timeStampHigh;
  int isW;
  float scLaserCorr, EoP, scEta, scPhi, scE, ES;
  int seedIeta, seedIphi, seedIx, seedIy, seedZside;

  ntu_DA->SetBranchAddress("runId", &runId);  
  ntu_DA->SetBranchAddress("timeStampHigh", &timeStampHigh);
  ntu_DA->SetBranchAddress("isW", &isW);
  ntu_DA->SetBranchAddress("ele1_scLaserCorr", &scLaserCorr);
  ntu_DA->SetBranchAddress("ele1_EOverP", &EoP);
  ntu_DA->SetBranchAddress("ele1_scEta", &scEta);
  ntu_DA->SetBranchAddress("ele1_scPhi", &scPhi);
  ntu_DA->SetBranchAddress("ele1_scE", &scE);
  ntu_DA->SetBranchAddress("ele1_es", &ES);
  ntu_DA->SetBranchAddress("ele1_seedIeta", &seedIeta);
  ntu_DA->SetBranchAddress("ele1_seedIphi", &seedIphi);
  ntu_DA->SetBranchAddress("ele1_seedIx", &seedIx);
  ntu_DA->SetBranchAddress("ele1_seedIy", &seedIy);
  ntu_DA->SetBranchAddress("ele1_seedZside", &seedZside);
  
  ntu_MC->SetBranchAddress("isW", &isW);
  ntu_MC->SetBranchAddress("ele1_scEta", &scEta);
  ntu_MC->SetBranchAddress("ele1_EOverP", &EoP);
  
  
  if( (dayMax != "") && (dayMin != "") )
  {
    int day,month,year;
    
    std::stringstream ssMin(dayMin);
    ssMin >> day >> month >> year;
    tm tmMin;
    tmMin.tm_sec = 0;
    tmMin.tm_min = 0;
    tmMin.tm_hour = 0;
    tmMin.tm_mday = day;
    tmMin.tm_mon = month-1;
    tmMin.tm_year = year-1900;
    t1 = timegm(&tmMin);
    
    std::stringstream ssMax(dayMax);
    ssMax >> day >> month >> year;    
    tm tmMax;
    tmMax.tm_sec = 0;
    tmMax.tm_min = 0;
    tmMax.tm_hour = 0;
    tmMax.tm_mday = day;
    tmMax.tm_mon = month-1;
    tmMax.tm_year = year-1900;
    t2 = timegm(&tmMax);
  }
Esempio n. 4
0
int main(int argc, char**argv){

  // open files and fill the tree chain
  std::string inputFileList = argv[1];
  std::string outFileName   = argv[2];
  std::string inputVariable = argv[3];
  std::string varRange      = argv[4];
  std::string varType       = argv[5];

  if(argc !=6) {std::cerr<<" Errors in parsing the parameters "<<std::endl; return 1; }
  

  TChain* chain = new TChain("simpleNtupleRecHits/SimpleNtupleEoverP");
  FillChain(*chain,inputFileList);
    
  // EE geometry
  TEndcapRings* eRings = new TEndcapRings();
  
  // define outfile
  TFile* outFile = new TFile(outFileName.c_str(),"RECREATE");
  
  // define histograms
  TH1F* h_occupancy_vsNvtx_EB = new TH1F("h_occupancy_vsNvtx_EB","",nBins_nVtx,nVtxMin,nVtxMax);
  TH1F* h_occupancy_vsNvtx_EE = new TH1F("h_occupancy_vsNvtx_EE","",nBins_nVtx,nVtxMin,nVtxMax);
  h_occupancy_vsNvtx_EB -> Sumw2();
  h_occupancy_vsNvtx_EE -> Sumw2();
  
  TH1F* h_occupancy_vsNavgPU_EB = new TH1F("h_occupancy_vsNavgPU_EB","",nBins_nAvgPU,nAvgPUMin,nAvgPUMax);
  TH1F* h_occupancy_vsNavgPU_EE = new TH1F("h_occupancy_vsNavgPU_EE","",nBins_nAvgPU,nAvgPUMin,nAvgPUMax);
  h_occupancy_vsNavgPU_EB -> Sumw2();
  h_occupancy_vsNavgPU_EE -> Sumw2();
  
  TH1F* h_occupancy_vsIeta_EB = new TH1F("h_occupancy_vsIeta_EB","",nBins_iEta,iEtaMin,iEtaMax);
  h_occupancy_vsIeta_EB -> Sumw2();
  TH1F* h_occupancy_vsIring_EE = new TH1F("h_occupancy_vsIring_EE","",nBins_iRing,iRingMin,iRingMax);
  h_occupancy_vsIring_EE -> Sumw2();
  
  std::map<float,TH1F*> map_recHitE_vsNvtx_EB; // for each vertex or PU number --> associated distribution
  std::map<float,TH1F*> map_recHitE_vsNvtx_EE;
  std::map<float,TH1F*> map_recHitE_nAvgPU10_vsNvtx_EB;
  std::map<float,TH1F*> map_recHitE_nAvgPU10_vsNvtx_EE;
  std::map<float,TH1F*> map_recHitE_nAvgPU20_vsNvtx_EB;
  std::map<float,TH1F*> map_recHitE_nAvgPU20_vsNvtx_EE;
  
  std::map<float,TH1F*> map_recHitE_vsNavgPU_EB;
  std::map<float,TH1F*> map_recHitE_vsNavgPU_EE;
  std::map<float,TH1F*> map_recHitE_nVtx10_vsNavgPU_EB;
  std::map<float,TH1F*> map_recHitE_nVtx10_vsNavgPU_EE;
  std::map<float,TH1F*> map_recHitE_nVtx20_vsNavgPU_EB;
  std::map<float,TH1F*> map_recHitE_nVtx20_vsNavgPU_EE;
  
  std::map<float,std::map<float,TH1F*> > map_recHitE_vsNavgPU_vsIeta_EB;
  std::map<float,std::map<float,TH1F*> > map_recHitE_vsNavgPU_vsIring_EE;
  
  // EB
  for(int bin = 1; bin <= nBins_nVtx; ++bin){

    char histoName[50];
    
    float binCenter  = h_occupancy_vsNvtx_EB -> GetBinCenter(bin);
    float binLowEdge = h_occupancy_vsNvtx_EB -> GetBinLowEdge(bin);
    float binHigEdge = h_occupancy_vsNvtx_EB -> GetBinLowEdge(bin) + h_occupancy_vsNvtx_EB->GetBinWidth(bin);
    sprintf(histoName,"hEB_recHitE_nVtx%02.1f-%02.1f",binLowEdge,binHigEdge);
    map_recHitE_vsNvtx_EB[binCenter] = new TH1F(histoName,"",2000,-4.,4.);    
    
    sprintf(histoName,"hEB_recHitE_nAvgPU10_nVtx%02.1f-%02.1f",binLowEdge,binHigEdge);
    map_recHitE_nAvgPU10_vsNvtx_EB[binCenter] = new TH1F(histoName,"",2000,-4.,4.);
    sprintf(histoName,"hEB_recHitE_nAvgPU20_nVtx%02.1f-%02.1f",binLowEdge,binHigEdge);
    map_recHitE_nAvgPU20_vsNvtx_EB[binCenter] = new TH1F(histoName,"",2000,-4.,4.);
  }
  
  for(int bin = 1; bin <= nBins_nAvgPU; ++bin){

    char histoName[50];
    
    float binCenter  = h_occupancy_vsNavgPU_EB -> GetBinCenter(bin);
    float binLowEdge = h_occupancy_vsNavgPU_EB -> GetBinLowEdge(bin);
    float binHigEdge = h_occupancy_vsNavgPU_EB -> GetBinLowEdge(bin) + h_occupancy_vsNavgPU_EB->GetBinWidth(bin);
    sprintf(histoName,"hEB_recHitE_nAvgPU%02.1f-%02.1f",binLowEdge,binHigEdge);
    map_recHitE_vsNavgPU_EB[binCenter] = new TH1F(histoName,"",2000,-4.,4.);    
    
    sprintf(histoName,"hEB_recHitE_nVtx10_nAvgPU%02.1f-%02.1f",binLowEdge,binHigEdge);
    map_recHitE_nVtx10_vsNavgPU_EB[binCenter] = new TH1F(histoName,"",2000,-4.,4.);
    sprintf(histoName,"hEB_recHitE_nVtx20_nAvgPU%02.1f-%02.1f",binLowEdge,binHigEdge);
    map_recHitE_nVtx20_vsNavgPU_EB[binCenter] = new TH1F(histoName,"",2000,-4.,4.);
    
    for(int iEtaBin = 1; iEtaBin <= nBins_iEta; ++iEtaBin)
    {
      float iEtaBinCenter  = h_occupancy_vsIeta_EB -> GetBinCenter(iEtaBin);
      float iEtaBinLowEdge = h_occupancy_vsIeta_EB -> GetBinLowEdge(iEtaBin);
      float iEtaBinHigEdge = h_occupancy_vsIeta_EB -> GetBinLowEdge(iEtaBin) + h_occupancy_vsIeta_EB->GetBinWidth(bin);
      sprintf(histoName,"hEB_recHitE_nAvgPU%02.1f-%02.1f_iEta%02.1f-%02.1f",binLowEdge,binHigEdge,iEtaBinLowEdge,iEtaBinHigEdge);
      (map_recHitE_vsNavgPU_vsIeta_EB[binCenter])[iEtaBinCenter] = new TH1F(histoName,"",2000,-2.,2.);
    }
  }
  
  // EE
  for(int bin = 1; bin <= nBins_nVtx; ++bin){

    char histoName[50];
    
    float binCenter  = h_occupancy_vsNvtx_EE -> GetBinCenter(bin);
    float binLowEdge = h_occupancy_vsNvtx_EE -> GetBinLowEdge(bin);
    float binHigEdge = h_occupancy_vsNvtx_EE -> GetBinLowEdge(bin) + h_occupancy_vsNvtx_EE->GetBinWidth(bin);
    sprintf(histoName,"hEE_recHitE_nVtx%02.1f-%02.1f",binLowEdge,binHigEdge);
    map_recHitE_vsNvtx_EE[binCenter] = new TH1F(histoName,"",2000,-4.,4.);    
    
    sprintf(histoName,"hEE_recHitE_nAvgPU10_nVtx%02.1f-%02.1f",binLowEdge,binHigEdge);
    map_recHitE_nAvgPU10_vsNvtx_EE[binCenter] = new TH1F(histoName,"",2000,-4.,4.);    
    sprintf(histoName,"hEE_recHitE_nAvgPU20_nVtx%02.1f-%02.1f",binLowEdge,binHigEdge);
    map_recHitE_nAvgPU20_vsNvtx_EE[binCenter] = new TH1F(histoName,"",2000,-4.,4.);    
  }
  
  for(int bin = 1; bin <= nBins_nAvgPU; ++bin){

    char histoName[50];
    
    float binCenter  = h_occupancy_vsNavgPU_EE -> GetBinCenter(bin);
    float binLowEdge = h_occupancy_vsNavgPU_EE -> GetBinLowEdge(bin);
    float binHigEdge = h_occupancy_vsNavgPU_EE -> GetBinLowEdge(bin) + h_occupancy_vsNavgPU_EE->GetBinWidth(bin);
    sprintf(histoName,"hEE_recHitE_nAvgPU%02.1f-%02.1f",binLowEdge,binHigEdge);
    map_recHitE_vsNavgPU_EE[binCenter] = new TH1F(histoName,"",2000,-4.,4.);    
    
    sprintf(histoName,"hEE_recHitE_nVtx10_nAvgPU%02.1f-%02.1f",binLowEdge,binHigEdge);
    map_recHitE_nVtx10_vsNavgPU_EE[binCenter] = new TH1F(histoName,"",2000,-4.,4.);    
    sprintf(histoName,"hEE_recHitE_nVtx20_nAvgPU%02.1f-%02.1f",binLowEdge,binHigEdge);
    map_recHitE_nVtx20_vsNavgPU_EE[binCenter] = new TH1F(histoName,"",2000,-4.,4.);    
    
    for(int iRingBin = 1; iRingBin <= nBins_iRing; ++iRingBin)
    {
      float iRingBinCenter  = h_occupancy_vsIring_EE -> GetBinCenter(iRingBin);
      float iRingBinLowEdge = h_occupancy_vsIring_EE -> GetBinLowEdge(iRingBin);
      float iRingBinHigEdge = h_occupancy_vsIring_EE -> GetBinLowEdge(iRingBin) + h_occupancy_vsIring_EE->GetBinWidth(bin);
      sprintf(histoName,"hEE_recHitE_nAvgPU%02.1f-%02.1f_iRing%02.1f-%02.1f",binLowEdge,binHigEdge,iRingBinLowEdge,iRingBinHigEdge);
      (map_recHitE_vsNavgPU_vsIring_EE[binCenter])[iRingBinCenter] = new TH1F(histoName,"",2000,-2.,2.);
    }
  }
  
  
  
  // define variables;
  int runId, lumiId;
  int timeStampHigh;
  int PV_n;
  float PUit_TrueNumInteractions;

  std::vector<float>* EBrecHit_E = new std::vector<float>;
  std::vector<float>* EErecHit_E = new std::vector<float>;
 
  std::vector<int>* EBrecHit_ietaORix = new std::vector<int>;
  std::vector<int>* EBrecHit_iphiORiy = new std::vector<int>;
  std::vector<int>* EErecHit_ietaORix = new std::vector<int>;
  std::vector<int>* EErecHit_iphiORiy = new std::vector<int>;
  std::vector<int>* EErecHit_zside = new std::vector<int>;
                                                                    
  chain -> SetBranchStatus("*",0); 
  chain -> SetBranchStatus("timeStampHigh",1);            chain -> SetBranchAddress("timeStampHigh",          &timeStampHigh);
  chain -> SetBranchStatus("runId",1);                    chain -> SetBranchAddress("runId",                  &runId);
  chain -> SetBranchStatus("lumiId",1);                   chain -> SetBranchAddress("lumiId",                 &lumiId);
  chain -> SetBranchStatus("PV_n",1);                     chain -> SetBranchAddress("PV_n",                   &PV_n);
  chain -> SetBranchStatus("PUit_TrueNumInteractions",1); chain -> SetBranchAddress("PUit_TrueNumInteractions",&PUit_TrueNumInteractions);

  
  chain -> SetBranchStatus("EBRecHit_E",1);               chain -> SetBranchAddress("EBRecHit_E",        &EBrecHit_E);
  chain -> SetBranchStatus("EERecHit_E",1);               chain -> SetBranchAddress("EERecHit_E",        &EErecHit_E);
  chain -> SetBranchStatus("EBRecHit_ietaORix",1);        chain -> SetBranchAddress("EBRecHit_ietaORix",        &EBrecHit_ietaORix);
  chain -> SetBranchStatus("EBRecHit_iphiORiy",1);        chain -> SetBranchAddress("EBRecHit_iphiORiy",        &EBrecHit_iphiORiy);
  chain -> SetBranchStatus("EERecHit_ietaORix",1);        chain -> SetBranchAddress("EERecHit_ietaORix",        &EErecHit_ietaORix);
  chain -> SetBranchStatus("EERecHit_iphiORiy",1);        chain -> SetBranchAddress("EERecHit_iphiORiy",        &EErecHit_iphiORiy);
  chain -> SetBranchStatus("EERecHit_zside",1);           chain -> SetBranchAddress("EERecHit_zside",           &EErecHit_zside);

  int    Var0;
  double Var1;
 
  if(varType == "int")    { chain -> SetBranchStatus(inputVariable.c_str(),1);  chain -> SetBranchAddress(inputVariable.c_str(),&Var0);}
  if(varType == "double") { chain -> SetBranchStatus(inputVariable.c_str(),1);  chain -> SetBranchAddress(inputVariable.c_str(),&Var1);}

  
  // loop over events                                                                                                                                             
  int nSelectedEvents = 0;

  std::vector<TString> mlist = TMVA::gTools().SplitString(varRange, '-' ); // min and max in the range
  
 
  for( int entry = 0; entry <chain->GetEntries() ; entry++ ) {


    if( entry%100 == 0 ) std::cout << ">>> reading entry " << entry << " / " << chain->GetEntries() << "\r" << std::flush;
    chain->GetEntry(entry);

    if( varType == "int"){ if( Var0 <= atoi(mlist.at(0).Data()) ) continue;
                           if( Var0 >= atoi(mlist.at(1).Data())) break;}  // ntuples should be ordered on the inputVariabe 
  
    if( varType == "double"){ if( Var1 <= atof(mlist.at(0).Data()) ) continue;
                              if( Var1 >= atof(mlist.at(1).Data())) break;}  // ntuples should be ordered on the inputVariab

    //    if( entry%100 == 0 ) std::cout << ">>> reading entry " << entry << " / " << chain->GetEntries() << "\r" << std::flush;
 
    ++nSelectedEvents;
    
          
    // fill ele1
    int bin = -1;
    int iEtaBin = -1;
    int iRingBin = -1;
    float iEtaBinCenter = -1.;
    float iRingBinCenter = -1.;
    float binCenter = -1.;
    TH1F* histo;
    
    for(unsigned int iEle = 0; iEle<EBrecHit_E->size(); iEle++){

      
      bin = h_occupancy_vsNvtx_EB -> Fill(PV_n);
      binCenter = h_occupancy_vsNvtx_EB -> GetBinCenter(bin);
      histo = map_recHitE_vsNvtx_EB[binCenter];
      if( PV_n > nVtxMin && PV_n < nVtxMax ) histo->Fill(EBrecHit_E->at(iEle));
      histo = map_recHitE_nAvgPU10_vsNvtx_EB[binCenter];
      if( PV_n > nVtxMin && PV_n < nVtxMax && PUit_TrueNumInteractions >= 9. && PUit_TrueNumInteractions < 11.) histo->Fill(EBrecHit_E->at(iEle));
      histo = map_recHitE_nAvgPU20_vsNvtx_EB[binCenter];
      if( PV_n > nVtxMin && PV_n < nVtxMax && PUit_TrueNumInteractions >= 19. && PUit_TrueNumInteractions < 21.) histo->Fill(EBrecHit_E->at(iEle));     
      bin = h_occupancy_vsNavgPU_EB -> Fill(PUit_TrueNumInteractions);
      binCenter = h_occupancy_vsNavgPU_EB -> GetBinCenter(bin);
      histo = map_recHitE_vsNavgPU_EB[binCenter];
      if( PUit_TrueNumInteractions > nAvgPUMin && PUit_TrueNumInteractions < nAvgPUMax ) histo->Fill(EBrecHit_E->at(iEle));     
      histo = map_recHitE_nVtx10_vsNavgPU_EB[binCenter];
      if( PUit_TrueNumInteractions > nAvgPUMin && PUit_TrueNumInteractions < nAvgPUMax && PV_n >= 9. && PV_n < 11.) histo->Fill(EBrecHit_E->at(iEle));
      histo = map_recHitE_nVtx20_vsNavgPU_EB[binCenter];
      if( PUit_TrueNumInteractions > nAvgPUMin && PUit_TrueNumInteractions < nAvgPUMax && PV_n >= 19. && PV_n < 21.) histo->Fill(EBrecHit_E->at(iEle));
      iEtaBin = h_occupancy_vsIeta_EB -> Fill(fabs(EBrecHit_ietaORix->at(iEle)));
      iEtaBinCenter = h_occupancy_vsIeta_EB -> GetBinCenter(iEtaBin);
      //  std::cout<<"binCenter "<<binCenter<<" EtaBin "<<iEtaBinCenter<<" EBrecHit_ietaORix "<<EBrecHit_ietaORix->at(iEle)<<std::endl;
       histo = (map_recHitE_vsNavgPU_vsIeta_EB[binCenter])[iEtaBinCenter];
      if( PUit_TrueNumInteractions > nAvgPUMin && PUit_TrueNumInteractions < nAvgPUMax ) histo->Fill(EBrecHit_E->at(iEle));
    }
    
    
    for(unsigned int iEle = 0; iEle<EErecHit_E->size(); iEle++){

      int Iring = eRings -> GetEndcapRing(EErecHit_ietaORix->at(iEle),EErecHit_iphiORiy->at(iEle),EErecHit_zside->at(iEle));
      
      bin = h_occupancy_vsNvtx_EE -> Fill(PV_n);
      binCenter = h_occupancy_vsNvtx_EE -> GetBinCenter(bin);
      histo = map_recHitE_vsNvtx_EE[binCenter];
      if( PV_n > nVtxMin && PV_n < nVtxMax )  histo->Fill(EErecHit_E->at(iEle));
      histo = map_recHitE_nAvgPU10_vsNvtx_EE[binCenter];
      if( PV_n > nVtxMin && PV_n < nVtxMax && PUit_TrueNumInteractions >= 9. && PUit_TrueNumInteractions < 11.) histo->Fill(EErecHit_E->at(iEle));
      histo = map_recHitE_nAvgPU20_vsNvtx_EE[binCenter];
      if( PV_n > nVtxMin && PV_n < nVtxMax && PUit_TrueNumInteractions >= 19. && PUit_TrueNumInteractions < 21.) histo->Fill(EErecHit_E->at(iEle));
      
      bin = h_occupancy_vsNavgPU_EE -> Fill(PUit_TrueNumInteractions);
      binCenter = h_occupancy_vsNavgPU_EE -> GetBinCenter(bin);
      histo = map_recHitE_vsNavgPU_EE[binCenter];
      if( PUit_TrueNumInteractions > nAvgPUMin && PUit_TrueNumInteractions < nAvgPUMax ) histo->Fill(EErecHit_E->at(iEle));
      histo = map_recHitE_nVtx10_vsNavgPU_EE[binCenter];
      if( PUit_TrueNumInteractions > nAvgPUMin && PUit_TrueNumInteractions < nAvgPUMax && PV_n >= 9. && PV_n < 11.) histo->Fill(EErecHit_E->at(iEle));
      histo = map_recHitE_nVtx20_vsNavgPU_EE[binCenter];
      if( PUit_TrueNumInteractions > nAvgPUMin && PUit_TrueNumInteractions < nAvgPUMax && PV_n >= 19. && PV_n < 21.) histo->Fill(EErecHit_E->at(iEle));
 
      iRingBin = h_occupancy_vsIring_EE -> Fill(fabs(Iring));
      iRingBinCenter = h_occupancy_vsIring_EE -> GetBinCenter(iRingBin);
      histo = (map_recHitE_vsNavgPU_vsIring_EE[binCenter])[iRingBinCenter];
      if( PUit_TrueNumInteractions > nAvgPUMin && PUit_TrueNumInteractions < nAvgPUMax ) histo->Fill(EErecHit_E->at(iEle));

    }
    
    
  }
  
  std::cout << std::endl;
  std::cout << ">>> selected " << nSelectedEvents << " / " << chain->GetEntries() << " good events" << std::endl;
  
  
  
  outFile -> cd();
  
  h_occupancy_vsNvtx_EB -> Write();
  h_occupancy_vsNvtx_EE -> Write();
  
  h_occupancy_vsNavgPU_EB -> Write();
  h_occupancy_vsNavgPU_EE -> Write();
  
  h_occupancy_vsIeta_EB  -> Write();
  h_occupancy_vsIring_EE -> Write();
  
  for(int bin = 1; bin <= nBins_nVtx; ++bin)
  {
    float binCenter;
    
    binCenter = h_occupancy_vsNvtx_EB -> GetBinCenter(bin);    
    map_recHitE_vsNvtx_EB[binCenter] -> Write();
    map_recHitE_nAvgPU10_vsNvtx_EB[binCenter] -> Write();
    map_recHitE_nAvgPU20_vsNvtx_EB[binCenter] -> Write();
    
    binCenter  = h_occupancy_vsNvtx_EE -> GetBinCenter(bin);    
    map_recHitE_vsNvtx_EE[binCenter] -> Write();
    map_recHitE_nAvgPU10_vsNvtx_EE[binCenter] -> Write();
    map_recHitE_nAvgPU20_vsNvtx_EE[binCenter] -> Write();
  }
  
  for(int bin = 1; bin <= nBins_nAvgPU; ++bin)
  {
    float binCenter;
    
    binCenter  = h_occupancy_vsNavgPU_EB -> GetBinCenter(bin);    
    map_recHitE_vsNavgPU_EB[binCenter] -> Write();
    map_recHitE_nVtx10_vsNavgPU_EB[binCenter] -> Write();
    map_recHitE_nVtx20_vsNavgPU_EB[binCenter] -> Write();
    
    for(int iEtaBin = 1; iEtaBin <= nBins_iEta; ++iEtaBin)
    {
      float iEtaBinCenter  = h_occupancy_vsIeta_EB -> GetBinCenter(iEtaBin);
      (map_recHitE_vsNavgPU_vsIeta_EB[binCenter])[iEtaBinCenter] -> Write();
    }
    
    binCenter  = h_occupancy_vsNavgPU_EE -> GetBinCenter(bin);    
    map_recHitE_vsNavgPU_EE[binCenter] -> Write();
    map_recHitE_nVtx10_vsNavgPU_EE[binCenter] -> Write();
    map_recHitE_nVtx20_vsNavgPU_EE[binCenter] -> Write();
    
    for(int iRingBin = 1; iRingBin <= nBins_iRing; ++iRingBin)
    {
      float iRingBinCenter  = h_occupancy_vsIring_EE -> GetBinCenter(iRingBin);
      (map_recHitE_vsNavgPU_vsIring_EE[binCenter])[iRingBinCenter] -> Write();
    }
    
  }
  
  outFile -> Close();
  
  
  return 0;
}
int main(int argc, char** argv)
{
  //Check if all nedeed arguments to parse are there
  if(argc != 2)
  {
    std::cerr << ">>>>> WZAnalysis::usage: " << argv[0] << " configFileName" << std::endl ;
    return 1;
  }
  
  std::string fileName(argv[1]);
  boost::shared_ptr<edm::ParameterSet> parameterSet = edm::readConfig(fileName);
  
  
  // "Input"
  edm::ParameterSet Input =  parameterSet -> getParameter<edm::ParameterSet>("Input");
  std::string inputFileList = Input.getParameter<std::string>("inputFileList");
  std::string jsonFileName  = Input.getParameter<std::string>("jsonFileName");
  
  
  // "Output"
  edm::ParameterSet Output =  parameterSet -> getParameter<edm::ParameterSet>("Output");
  std::string outputRootFilePath = Output.getParameter<std::string>("outputRootFilePath");
  std::string outputRootFileName = Output.getParameter<std::string>("outputRootFileName");
  std::string outputRootFullFileName = outputRootFilePath + "/" + outputRootFileName + ".root";
  
  
  // "Options"
  edm::ParameterSet Options =  parameterSet -> getParameter<edm::ParameterSet>("Options");
  int entryMIN       = Options.getParameter<int>("entryMIN");
  int entryMAX       = Options.getParameter<int>("entryMAX");
  int entryMODULO    = Options.getParameter<int>("entryMODULO");
  int jsonFlag       = Options.getParameter<int>("jsonFlag");
  int verbosity      = Options.getParameter<int>("verbosity");
  
  
  // Get total number of events
  std::cout << ">>> WZAnalysis::Get number of events" << std::endl;
  std::map<int, int> beginEvents      = GetTotalEvents("AllPassFilterBegin/passedEvents",            inputFileList.c_str());
  std::map<int, int> goodVertexEvents = GetTotalEvents("AllPassFilterGoodVertexFilter/passedEvents", inputFileList.c_str());
  std::map<int, int> noScrapingEvents = GetTotalEvents("AllPassFilterNoScrapingFilter/passedEvents", inputFileList.c_str());
  std::map<int, int> HBHENoiseEvents  = GetTotalEvents("AllPassFilterHBHENoiseFilter/passedEvents",  inputFileList.c_str());
  std::map<int, int> electronEvents   = GetTotalEvents("AllPassFilterElectronFilter/passedEvents",   inputFileList.c_str());
  
  
  
  // Get run/LS map from JSON file
  std::cout << ">>> WZPreselection::Get run/LS map from JSON file" << std::endl;
  std::map<int, std::vector<std::pair<int, int> > > jsonMap;
  jsonMap = readJSONFile(jsonFileName);
  
  
  
  // define HLT paths
  std::vector<std::pair<std::string,std::pair<int,int> > > WHLTPathNames;
  
  std::pair<int,int> WRunRanges1(160404,161176);
  std::pair<std::string,std::pair<int,int> > WHLTPathName1("HLT_Ele27_CaloIdVT_CaloIsoT_TrkIdT_TrkIsoT_v1",WRunRanges1);
  std::pair<int,int> WRunRanges2(161216,163261);
  std::pair<std::string,std::pair<int,int> > WHLTPathName2("HLT_Ele27_CaloIdVT_CaloIsoT_TrkIdT_TrkIsoT_v2",WRunRanges2);
  std::pair<int,int> WRunRanges3(163269,163869);
  std::pair<std::string,std::pair<int,int> > WHLTPathName3("HLT_Ele27_CaloIdVT_CaloIsoT_TrkIdT_TrkIsoT_v3",WRunRanges3);
  std::pair<int,int> WRunRanges4(165088,165633);
  std::pair<std::string,std::pair<int,int> > WHLTPathName4("HLT_Ele32_CaloIdVT_CaloIsoT_TrkIdT_TrkIsoT_v3",WRunRanges4);
  std::pair<int,int> WRunRanges5(165970,166967);
  std::pair<std::string,std::pair<int,int> > WHLTPathName5("HLT_Ele25_WP80_PFMT40_v1",WRunRanges5);
  std::pair<int,int> WRunRanges6(167039,167913);
  std::pair<std::string,std::pair<int,int> > WHLTPathName6("HLT_Ele27_WP80_PFMT50_v1",WRunRanges6);
  std::pair<int,int> WRunRanges7(170249,173198);
  std::pair<std::string,std::pair<int,int> > WHLTPathName7("HLT_Ele32_WP70_PFMT50_v3",WRunRanges7);
  std::pair<int,int> WRunRanges8(173236,999999);
  std::pair<std::string,std::pair<int,int> > WHLTPathName8("HLT_Ele32_WP70_PFMT50_v4",WRunRanges8);
  
  WHLTPathNames.push_back(WHLTPathName1);
  WHLTPathNames.push_back(WHLTPathName2);
  WHLTPathNames.push_back(WHLTPathName3);
  WHLTPathNames.push_back(WHLTPathName4);
  WHLTPathNames.push_back(WHLTPathName5);
  WHLTPathNames.push_back(WHLTPathName6);
  WHLTPathNames.push_back(WHLTPathName7);
  WHLTPathNames.push_back(WHLTPathName8);
  
  
  
  std::vector<std::pair<std::string,std::pair<int,int> > > ZHLTPathNames;
  
  std::pair<int,int> ZRunRanges1(160404,161176);
  std::pair<std::string,std::pair<int,int> > ZHLTPathName1("HLT_Ele17_CaloIdL_CaloIsoVL_Ele8_CaloIdL_CaloIsoVL_v1",ZRunRanges1);
  std::pair<int,int> ZRunRanges2(161216,163261);
  std::pair<std::string,std::pair<int,int> > ZHLTPathName2("HLT_Ele17_CaloIdL_CaloIsoVL_Ele8_CaloIdL_CaloIsoVL_v2",ZRunRanges2);
  std::pair<int,int> ZRunRanges3(163269,163869);
  std::pair<std::string,std::pair<int,int> > ZHLTPathName3("HLT_Ele17_CaloIdL_CaloIsoVL_Ele8_CaloIdL_CaloIsoVL_v3",ZRunRanges3);
  std::pair<int,int> ZRunRanges4(165088,165633);
  std::pair<std::string,std::pair<int,int> > ZHLTPathName4("HLT_Ele17_CaloIdL_CaloIsoVL_Ele8_CaloIdL_CaloIsoVL_v4",ZRunRanges4);
  std::pair<int,int> ZRunRanges5(165970,166967);
  std::pair<std::string,std::pair<int,int> > ZHLTPathName5("HLT_Ele17_CaloIdL_CaloIsoVL_Ele8_CaloIdL_CaloIsoVL_v5",ZRunRanges5);
  std::pair<int,int> ZRunRanges6(167039,167913);
  std::pair<std::string,std::pair<int,int> > ZHLTPathName6("HLT_Ele17_CaloIdL_CaloIsoVL_Ele8_CaloIdL_CaloIsoVL_v6",ZRunRanges6);
  std::pair<int,int> ZRunRanges7(170249,170759);
  std::pair<std::string,std::pair<int,int> > ZHLTPathName7("HLT_Ele17_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_Ele8_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_v6",ZRunRanges7);
  std::pair<int,int> ZRunRanges8(170826,173198);
  std::pair<std::string,std::pair<int,int> > ZHLTPathName8("HLT_Ele17_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_Ele8_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_v7",ZRunRanges8);
  std::pair<int,int> ZRunRanges9(173236,999999);
  std::pair<std::string,std::pair<int,int> > ZHLTPathName9("HLT_Ele17_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_Ele8_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_v8",ZRunRanges9);
  
  ZHLTPathNames.push_back(ZHLTPathName1);
  ZHLTPathNames.push_back(ZHLTPathName2);
  ZHLTPathNames.push_back(ZHLTPathName3);
  ZHLTPathNames.push_back(ZHLTPathName4);
  ZHLTPathNames.push_back(ZHLTPathName5);
  ZHLTPathNames.push_back(ZHLTPathName6);
  ZHLTPathNames.push_back(ZHLTPathName7);
  ZHLTPathNames.push_back(ZHLTPathName8);
  ZHLTPathNames.push_back(ZHLTPathName9);
  
  
  
  // Open tree
  std::cout << ">>> WZAnalysis::Open old tree" << std::endl;
  std::string treeName = "simpleNtuple/SimpleNtuple";
  TChain* chain = new TChain(treeName.c_str());
  if(!FillChain(*chain, inputFileList.c_str())) return 1;
  treeReader reader((TTree*)(chain), false);
  
  
  
  // Open output root file
  outputRootFileName += ".root";
  
  
  
  // define histograms
  std::cout << ">>> WZAnalysis::Define histograms" << std::endl;
  
  int nStep = 10;
  TH1F* events = new TH1F("events", "events", nStep, 0., 1.*nStep);
  std::map<int, int> stepEvents;
  std::map<int, std::string> stepNames;
  
  
  
  // define the reduced ntuple 
  WZAnalysisVariablesSingleXtal vars;
  InitializeWZAnalysisTree(vars,outputRootFullFileName);
  
  
   
  //**********************
  // STEP 1 - Begin events
  int step = 1;
  SetStepNames(stepNames, "All events", step, verbosity);
  stepEvents[step] = beginEvents[1];
  
  
  
  //****************************
  // STEP 2 - Good Vertex events
  step = 2;
  SetStepNames(stepNames, "Good vertex", step, verbosity);
  stepEvents[step] = goodVertexEvents[1];
  
  
  
  //*********************
  // STEP 3 - No Scraping
  step = 3;
  SetStepNames(stepNames, "No scraping", step, verbosity);
  stepEvents[step] = noScrapingEvents[1];
  
  
  
  //*********************
  // STEP 4 - HBHE Noise
  step = 4;
  SetStepNames(stepNames, "HBHE Noise", step, verbosity);
  stepEvents[step] = HBHENoiseEvents[1];
  
  
  
  //******************
  // STEP 5 - Electron
  step = 5;
  SetStepNames(stepNames, "Electron", step, verbosity);
  stepEvents[step] = electronEvents[1];
   
  
  
  //*********************
  // LOOP OVER THE EVENTS
  std::cout << ">>>>> WZAnalysis::Read " << chain -> GetEntries() << " entries" << std::endl;  
  for(int entry = entryMIN ; entry < chain -> GetEntries() ; ++entry)
  {
    reader.GetEntry(entry);
    if((entry%entryMODULO) == 0) std::cout << ">>>>> WZAnalysis::GetEntry " << entry << std::endl;   
    if(entry == entryMAX) break;
      
    // clear variables
    ClearWZAnalysisVariables(vars);    
    
    // event variables
    vars.runId   = reader.GetInt("runId")->at(0);
    vars.lumiId  = reader.GetInt("lumiId")->at(0);
    
    
    //**************************
    // STEP 6 - run/LS selection
    step = 6;
    SetStepNames(stepNames, "run/LS", step, verbosity);
    
    bool skipEvent = false;
    
    if(AcceptEventByRunAndLumiSection(vars.runId,vars.lumiId,jsonMap) == false)
      skipEvent = true;

    if( (jsonFlag == 1) && (skipEvent == true) ) continue;
    stepEvents[step] += 1;
    
    //***********************
    // STEP 7 - HLT selection
    step += 1;
    SetStepNames(stepNames, "HLT", step, verbosity);
    
    
    skipEvent = true;
    bool isWHLT = false;
    bool isZHLT = false;
    
    if( verbosity == 1 )
    {
      std::vector<std::string> HLT_names = *(reader.GetString("HLT_Names"));
      for(unsigned int HLTIt = 0; HLTIt < HLT_names.size(); ++HLTIt)
        std::cout << "HLT bit " << HLTIt 
            << ":   "     << HLT_names.at(HLTIt)
            << std::endl;
    }
    
    // W triggers
    for(unsigned int HLTIt = 0; HLTIt < WHLTPathNames.size(); ++HLTIt)
    {
      if( AcceptHLTPath(reader, WHLTPathNames.at(HLTIt)) == true )
        skipEvent = false;
      isWHLT = true;
    }
    // Z triggers
    for(unsigned int HLTIt = 0; HLTIt < ZHLTPathNames.size(); ++HLTIt)
    {
      if( AcceptHLTPath(reader, ZHLTPathNames.at(HLTIt)) == true )
        skipEvent = false;
      isZHLT = true; 
    }
    
    if( skipEvent == true ) continue;
    stepEvents[step] += 1;    
        
    
    
    
    
    
    //**************************
    // STEP 8 - cut on electrons
    step += 1;
    SetStepNames(stepNames, "1/2 ele", step, verbosity);
    
    
    int nTightEle = 0;
    int nMediumEle = 0;
    int nLooseEle = 0;
    std::map<float,int> eleIts;
    
    // loop on electrons
    for(unsigned int eleIt = 0; eleIt < (reader.Get4V("electrons")->size()); ++eleIt)
    {
      ROOT::Math::XYZTVector ele = reader.Get4V("electrons")->at(eleIt);
      float pt = ele.pt();
      float eta = ele.eta();
      
      float tkIso  = reader.GetFloat("electrons_tkIso03")->at(eleIt);
      float emIso  = reader.GetFloat("electrons_emIso03")->at(eleIt);
      float hadIso = reader.GetFloat("electrons_hadIso03_1")->at(eleIt) + 
          reader.GetFloat("electrons_hadIso03_2")->at(eleIt);
      float combIso = tkIso + emIso + hadIso;
      
      int isEB = reader.GetInt("electrons_isEB")->at(eleIt);
      
      float sigmaIetaIeta = reader.GetFloat("electrons_sigmaIetaIeta")->at(eleIt);
      float DetaIn        = reader.GetFloat("electrons_deltaEtaIn")->at(eleIt);
      float DphiIn        = reader.GetFloat("electrons_deltaPhiIn")->at(eleIt);
      float HOverE        = reader.GetFloat("electrons_hOverE")->at(eleIt);
      
      int mishits             = reader.GetInt("electrons_mishits")->at(eleIt);
      int nAmbiguousGsfTracks = reader.GetInt("electrons_nAmbiguousGsfTracks")->at(eleIt);
      float dist = reader.GetFloat("electrons_dist")->at(eleIt);
      float dcot = reader.GetFloat("electrons_dcot")->at(eleIt);
      
      
      // tight electrons
      bool isTightElectron = false;
      if(
         (pt > 20.) &&
         (fabs(eta) < 2.5) &&
          // EleID WP80 - 2010
         ( ( (isEB == 1) && (combIso/pt    < 0.070) ) || ( (isEB == 0) && (combIso/pt    < 0.060) ) ) &&
         ( ( (isEB == 1) && (sigmaIetaIeta < 0.010) ) || ( (isEB == 0) && (sigmaIetaIeta < 0.030) ) ) &&
         ( ( (isEB == 1) && (fabs(DphiIn)  < 0.060) ) || ( (isEB == 0) && (fabs(DphiIn)  < 0.030) ) ) &&
         ( ( (isEB == 1) && (fabs(DetaIn)  < 0.004) ) || ( (isEB == 0) && (fabs(DetaIn)  < 0.007) ) ) &&
          //( ( (isEB == 1) && (HOverE        < 0.040) ) || ( (isEB == 0) && (HOverE        < 0.025) ) ) &&
         ( mishits == 0 ) &&
         ( nAmbiguousGsfTracks == 0 ) &&
         ( ( fabs(dist) > 0.02 ) || ( fabs(dcot) > 0.02 ) )
        )
      {
        isTightElectron = true;
        ++nTightEle;
        eleIts[1./pt] = eleIt;
      }
      
      
      // semi-tight electrons
      if( isTightElectron == true ) continue;
      //      bool isMediumElectron = false;
      if(
         (pt > 12.) &&
         (fabs(eta) < 2.5) &&
          // EleID WP80 - 2010
         ( ( (isEB == 1) && (combIso/pt    < 0.070) ) || ( (isEB == 0) && (combIso/pt    < 0.060) ) ) &&
         ( ( (isEB == 1) && (sigmaIetaIeta < 0.010) ) || ( (isEB == 0) && (sigmaIetaIeta < 0.030) ) ) &&
         ( ( (isEB == 1) && (fabs(DphiIn)  < 0.060) ) || ( (isEB == 0) && (fabs(DphiIn)  < 0.030) ) ) &&
         ( ( (isEB == 1) && (fabs(DetaIn)  < 0.004) ) || ( (isEB == 0) && (fabs(DetaIn)  < 0.007) ) ) &&
          //( ( (isEB == 1) && (HOverE        < 0.040) ) || ( (isEB == 0) && (HOverE        < 0.025) ) ) &&
         ( mishits == 0 ) &&
         ( nAmbiguousGsfTracks == 0 ) &&
         ( ( fabs(dist) > 0.02 ) || ( fabs(dcot) > 0.02 ) )
        )
      {
	//        isMediumElectron = true;
        ++nMediumEle;
        eleIts[1./pt] = eleIt;
      }
      
      
      // loose electrons
      if( isTightElectron == true ) continue;
      if( 
          (pt > 10.) &&
          (fabs(eta) < 2.5) &&
          // EleID WP95 - 2010
          ( ( (isEB == 1) && (combIso/pt    < 0.150) ) || ( (isEB == 0) && (combIso/pt    < 0.100) ) ) &&
          ( ( (isEB == 1) && (sigmaIetaIeta < 0.010) ) || ( (isEB == 0) && (sigmaIetaIeta < 0.030) ) ) &&
          ( ( (isEB == 1) && (fabs(DphiIn)  < 0.800) ) || ( (isEB == 0) && (fabs(DphiIn)  < 0.700) ) ) &&
          ( ( (isEB == 1) && (fabs(DetaIn)  < 0.007) ) || ( (isEB == 0) && (fabs(DetaIn)  < 0.010) ) ) &&
          ( ( (isEB == 1) && (HOverE        < 0.150) ) || ( (isEB == 0) && (HOverE        < 0.070) ) )
        )
      {
        ++nLooseEle;
      }
      
    } // loop on electrons
    
    
    
    int nLooseMu = 0;
    
    // loop on muons
    for(unsigned int muIt = 0; muIt < (reader.Get4V("muons")->size()); ++muIt)
    {
      ROOT::Math::XYZTVector mu = reader.Get4V("muons")->at(muIt);
      float pt = mu.pt();
      float eta = mu.eta();
      
      float tkIso  = reader.GetFloat("muons_tkIso03")->at(muIt);
      float emIso  = reader.GetFloat("muons_emIso03")->at(muIt);
      float hadIso = reader.GetFloat("muons_hadIso03")->at(muIt);
      float combIso = tkIso + emIso + hadIso;
      
      int global = reader.GetInt("muons_global")->at(muIt);

      if( (pt > 10.) &&
           (fabs(eta) < 2.5) &&
           (combIso/pt < 0.20) &&
           (global == 1) )
      {
        ++nLooseMu;
      }
    }
    
    
    // cuts
    if( verbosity == 1 )
      std::cout << " nTightEle = "  << nTightEle
          << " nMediumEle = " << nMediumEle
          << " nLooseEle = "  << nLooseEle
          << " nLooseMu = "   << nLooseMu
          << std::endl;
    if( nTightEle < 1 ) continue;
    if( nTightEle > 2 ) continue;
    if( nMediumEle > 1 ) continue;
    if( nLooseEle > 0 ) continue;
    if( nLooseMu > 0 ) continue;
    stepEvents[step] += 1;
    
    
    // set electron variables
    std::map<float,int>::const_iterator mapIt = eleIts.begin();

    //PhotonFix::initialise("4_2");

    if( (nTightEle == 1) && (nMediumEle == 0) )
    {
      SetElectron1Variables(vars,reader,mapIt->second);
      //PhotonFix Correction1 (vars.ele1_scE,vars.ele1_scEta,vars.ele1_scPhi,vars.ele1_e3x3/vars.ele1_scE);
      //vars.ele1_scLocalContCorr_DK = Correction1.fixedEnergy()/vars.ele1_scE;
    }
    
    mapIt = eleIts.begin();
    if( (nTightEle == 2) || (nTightEle == 1 && nMediumEle == 1) )
    {
      SetElectron1Variables(vars,reader,mapIt->second);
      //PhotonFix Correction1 (vars.ele1_scE,vars.ele1_scEta,vars.ele1_scPhi,vars.ele1_e3x3/vars.ele1_scE);
      //vars.ele1_scLocalContCorr_DK = Correction1.fixedEnergy()/vars.ele1_scE;
      
      ++mapIt;
      
      SetElectron2Variables(vars,reader,mapIt->second);
      //PhotonFix Correction2 (vars.ele2_scE,vars.ele2_scEta,vars.ele2_scPhi,vars.ele2_e3x3/vars.ele2_scE);
      //vars.ele2_scLocalContCorr_DK = Correction2.fixedEnergy()/vars.ele2_scE;
    }
    
    
    // set met variables
    SetMetVariables(vars,reader);
    
    // set di-electron variables
    if( (nTightEle == 2) || (nTightEle == 1 && nMediumEle == 1) )
    {
      SetDiElectronVariables(vars,reader);
    }
    
    
    
    
    
    
    //***********************
    // STEP 9 - W selection
    step += 1;
    SetStepNames(stepNames, "W selection", step, verbosity);
    
    
    if( (nTightEle == 1) && (nMediumEle == 0) )
    {
      if( isWHLT == false ) continue;
      if( vars.ele1_pt < 30. ) continue;
      // EleID WP70 - 2010
      if( ( vars.ele1_isEB == 1 ) && ( (vars.ele1_tkIso+vars.ele1_emIso+vars.ele1_hadIso)/vars.ele1_pt > 0.04 ) ) continue;
      if( ( vars.ele1_isEB == 1 ) && ( fabs(vars.ele1_DphiIn) > 0.030 ) ) continue;
      if( ( vars.ele1_isEB == 1 ) && ( fabs(vars.ele1_DetaIn) > 0.004 ) ) continue;
      if( ( vars.ele1_isEB == 1 ) && ( vars.ele1_HOverE > 0.025 ) ) continue;
      if( ( vars.ele1_isEB == 0 ) && ( (vars.ele1_tkIso+vars.ele1_emIso+vars.ele1_hadIso)/vars.ele1_pt > 0.03 ) ) continue;
      if( ( vars.ele1_isEB == 0 ) && ( fabs(vars.ele1_DphiIn) > 0.020 ) ) continue;
      if( ( vars.ele1_isEB == 0 ) && ( fabs(vars.ele1_DetaIn) > 0.005 ) ) continue;
      if( ( vars.ele1_isEB == 0 ) && ( vars.ele1_HOverE > 0.025 ) ) continue;
      
      if( vars.met_et       < 25.00 ) continue;
      if( vars.ele1Met_mt   < 50.00 ) continue;
      if( vars.ele1Met_Dphi <  1.57 ) continue;
      stepEvents[step] += 1;
      
      
      vars.isW = 1;
      vars.isZ = 0;
      
      
      // fill the reduced tree
      FillWZAnalysisTree(vars);
    }
    
    
    
    
    
    
    //***********************
    // STEP 10 - Z selection
    step += 1;
    SetStepNames(stepNames, "Z selection", step, verbosity);
    
    
    if( (nTightEle == 2) || (nTightEle == 1 && nMediumEle == 1) )
    {
      if( isZHLT == false ) continue;
      if( vars.met_et     >  40. ) continue;
      if( vars.ele1ele2_m <  70. ) continue;
      if( vars.ele1ele2_m > 110. ) continue;
      if( (vars.ele1_charge * vars.ele2_charge) != -1. ) continue;
      stepEvents[step] += 1;
      
      
      vars.isW = 0;
      vars.isZ = 1;
      
      
      // fill the reduced tree
      FillWZAnalysisTree(vars);
    }
    
    
    
  } // loop over the events
  
  
  
  
  
  
  // save the reduced tree
  DeleteWZAnalysisVariables(vars);
  
  
  // save the histograms
  TFile* outputRootFile = new TFile((outputRootFullFileName).c_str(), "UPDATE");
  outputRootFile -> cd();
  
  for(step = 1; step <= nStep; ++step)
  {
    events -> SetBinContent(step, stepEvents[step]);
    events -> GetXaxis() -> SetBinLabel(step, stepNames[step].c_str());
  }

  events -> Write();
  outputRootFile -> Close();
  
  
  return 0;
}
Esempio n. 6
0
int main (int argc, char ** argv)
{

	///Check if all nedeed arguments to parse are there
	if(argc != 2) {
		std::cerr << ">>>>> FastCalibrator::usage: " << argv[0] << " configFileName" << std::endl ;
		return 1;
	}

	std::string configFileName = argv[1];
	boost::shared_ptr<edm::ParameterSet> parameterSet = edm::readConfig(configFileName);
	edm::ParameterSet Options = parameterSet -> getParameter<edm::ParameterSet>("Options");
	parameterSet.reset();

	std::string inputList = "NULL";
	if(Options.existsAs<std::string>("inputList"))
		inputList = Options.getParameter<std::string>("inputList");
	else {
		std::cout << " Exit from code, no input list found" << std::endl;
		std::exit(EXIT_FAILURE);
	}

	std::string inputFileDeadXtal = "NULL";
	if(Options.existsAs<std::string>("inputFileDeadXtal"))
		inputFileDeadXtal = Options.getParameter<std::string>("inputFileDeadXtal");
	else {
		std::cout << " No input File Dead Xtal found! " << std::endl;
	}

	std::string inputTree = "NULL";
	if(Options.existsAs<std::string>("inputTree"))
		inputTree = Options.getParameter<std::string>("inputTree");
	else {
		std::cout << " Exit from code, no input tree found" << std::endl;
		std::exit(EXIT_FAILURE);
	}

	std::string jsonFileName = "NULL";
	if(Options.existsAs<std::string>("jsonFileName"))
		jsonFileName = Options.getParameter<std::string>("jsonFileName");
	else {
		std::cout << " Exit from code, no jsonFile found" << std::endl;
		std::exit(EXIT_FAILURE);
	}

	std::map<int, std::vector<std::pair<int, int> > > jsonMap;
	jsonMap = readJSONFile(jsonFileName);

	std::string miscalibMap = "NULL";
	if(Options.existsAs<std::string>("miscalibMap"))
		miscalibMap = Options.getParameter<std::string>("miscalibMap");
	else {
		std::cout << " no miscalib map found" << std::endl;
	}

	bool isMiscalib = false;
	if(Options.existsAs<bool>("isMiscalib"))
		isMiscalib = Options.getParameter<bool>("isMiscalib");

	bool isSaveEPDistribution = false;
	if(Options.existsAs<bool>("isSaveEPDistribution"))
		isSaveEPDistribution = Options.getParameter<bool>("isSaveEPDistribution");

	bool isMCTruth = false;
	if(Options.existsAs<bool>("isMCTruth"))
		isMCTruth = Options.getParameter<bool>("isMCTruth");

	bool isEPselection = false;
	if(Options.existsAs<bool>("isEPselection"))
		isEPselection = Options.getParameter<bool>("isEPselection");

	bool isPtCut = false;
	if(Options.existsAs<bool>("isPtCut"))
		isPtCut = Options.getParameter<bool>("isPtCut");

	double PtMin = 0.;
	if(Options.existsAs<double>("PtMin"))
		PtMin = Options.getParameter<double>("PtMin");

	bool isfbrem = false;
	if(Options.existsAs<bool>("isfbrem"))
		isfbrem = Options.getParameter<bool>("isfbrem");

	double fbremMax = 100.;
	if(Options.existsAs<double>("fbremMax"))
		fbremMax = Options.getParameter<double>("fbremMax");

	bool isR9selection = false;
	if(Options.existsAs<bool>("isR9selection"))
		isR9selection = Options.getParameter<bool>("isR9selection");

	double R9Min = -1.;
	if(Options.existsAs<double>("R9Min"))
		R9Min = Options.getParameter<double>("R9Min");

	int miscalibMethod = 1;
	if(Options.existsAs<double>("miscalibMethod"))
		miscalibMethod = Options.getParameter<double>("miscalibMethod");

	std::string inputMomentumScale = "NULL";
	if(Options.existsAs<std::string>("inputMomentumScale"))
		inputMomentumScale = Options.getParameter<std::string>("inputMomentumScale");

	std::string typeEB = "NULL";
	if(Options.existsAs<std::string>("typeEB"))
		typeEB = Options.getParameter<std::string>("typeEB");

	std::string typeEE = "NULL";
	if(Options.existsAs<std::string>("typeEE"))
		typeEE = Options.getParameter<std::string>("typeEE");
	int nRegionsEE = GetNRegionsEE(typeEE);

	std::string outputPath = "output/Oct22_Run2012ABC_Cal_Dic2012/";
	if(Options.existsAs<std::string>("outputPath"))
		outputPath = Options.getParameter<std::string>("outputPath");
	system(("mkdir -p " + outputPath).c_str());

	std::string outputFile = "FastCalibrator_Oct22_Run2012ABC_Cal_Dic2012";
	if(Options.existsAs<std::string>("outputFile"))
		outputFile = Options.getParameter<std::string>("outputFile");

	int numberOfEvents = -1;
	if(Options.existsAs<int>("numberOfEvents"))
		numberOfEvents = Options.getParameter<int>("numberOfEvents");

	int useZ = 1;
	if(Options.existsAs<int>("useZ"))
		useZ = Options.getParameter<int>("useZ");

	int useW = 1;
	if(Options.existsAs<int>("useW"))
		useW = Options.getParameter<int>("useW");

	int splitStat = 0;
	if(Options.existsAs<int>("splitStat"))
		splitStat = Options.getParameter<int>("splitStat");

	int nLoops = 20;
	if(Options.existsAs<int>("nLoops"))
		nLoops = Options.getParameter<int>("nLoops");

	bool isDeadTriggerTower = false;
	if(Options.existsAs<bool>("isDeadTriggerTower"))
		isDeadTriggerTower = Options.getParameter<bool>("isDeadTriggerTower");


	/// Acquistion input ntuples
	TChain * tree = new TChain (inputTree.c_str());
	FillChain(*tree, inputList);

	/// open calibration momentum graph
	TFile* f4 = new TFile((inputMomentumScale + "_" + typeEB + "_" + typeEE + ".root").c_str());
	std::vector<TGraphErrors*> g_EoC_EE;

	for(int i = 0; i < nRegionsEE; ++i) {
		TString Name = Form("g_EoC_EE_%d", i);
		g_EoC_EE.push_back( (TGraphErrors*)(f4->Get(Name)) );
	}

	///Use the whole sample statistics if numberOfEvents < 0
	if ( numberOfEvents < 0 ) numberOfEvents = tree->GetEntries();


	/// run in normal mode: full statistics
	if ( splitStat == 0 ) {

		TString name ;
		TString name_tmp;

		if(isMiscalib == true && useZ == 1 && isR9selection == true && isEPselection == false && isfbrem == false && isPtCut == false )
			name_tmp = Form ("%s_WZ_R9_miscalib_EE", outputFile.c_str());
		else if(isMiscalib == true && useZ == 1 && isR9selection == false && isEPselection == false && isfbrem == true && isPtCut == false )
			name_tmp = Form ("%s_WZ_Fbrem_miscalib_EE", outputFile.c_str());
		else if(isMiscalib == true && useZ == 1 && isR9selection == true && isEPselection == false && isfbrem == false && isPtCut == true )
			name_tmp = Form ("%s_WZ_PT_miscalib_EE", outputFile.c_str());
		else if(isMiscalib == true && useZ == 1 && isR9selection == true && isEPselection == true && isfbrem == false && isPtCut == false )
			name_tmp = Form ("%s_WZ_EP_miscalib_EE", outputFile.c_str());
		else if(isMiscalib == true && useZ == 1 && isEPselection == false && isR9selection == false && isPtCut == false && isfbrem == false  )
			name_tmp = Form ("%s_WZ_noEP_miscalib_EE", outputFile.c_str());

		else if(isMiscalib == false && useZ == 1 && isR9selection == true && isEPselection == false && isfbrem == false && isPtCut == false )
			name_tmp = Form ("%s_WZ_R9_EE", outputFile.c_str());
		else if(isMiscalib == false && useZ == 1 && isR9selection == false && isEPselection == false && isfbrem == true && isPtCut == false )
			name_tmp = Form ("%s_WZ_Fbrem_EE", outputFile.c_str());
		else if(isMiscalib == false && useZ == 1 && isR9selection == true && isEPselection == false && isfbrem == false && isPtCut == true )
			name_tmp = Form ("%s_WZ_PT_EE", outputFile.c_str());
		else if(isMiscalib == false && useZ == 1 && isR9selection == true && isEPselection == true && isfbrem == false && isPtCut == false )
			name_tmp = Form ("%s_WZ_EP_EE", outputFile.c_str());
		else if(isMiscalib == false && useZ == 1 && isEPselection == false && isR9selection == false && isPtCut == false && isfbrem == false  )
			name_tmp = Form ("%s_WZ_noEP_EE", outputFile.c_str());



		else if(isMiscalib == true && useZ == 0 && isR9selection == true && isEPselection == false && isfbrem == false && isPtCut == false )
			name_tmp = Form ("%s_W_R9_miscalib_EE", outputFile.c_str());
		else if(isMiscalib == true && useZ == 0 && isR9selection == false && isEPselection == false && isfbrem == true && isPtCut == false )
			name_tmp = Form ("%s_W_Fbrem_miscalib_EE", outputFile.c_str());
		else if(isMiscalib == true && useZ == 0 && isR9selection == true && isEPselection == false && isfbrem == false && isPtCut == true )
			name_tmp = Form ("%s_W_PT_miscalib_EE", outputFile.c_str());
		else if(isMiscalib == true && useZ == 0 && isR9selection == true && isEPselection == true && isfbrem == false && isPtCut == false )
			name_tmp = Form ("%s_W_EP_miscalib_EE", outputFile.c_str());
		else if(isMiscalib == true && useZ == 0 && isEPselection == false && isR9selection == false && isPtCut == false && isfbrem == false  )
			name_tmp = Form ("%s_W_noEP_miscalib_EE", outputFile.c_str());

		else if(isMiscalib == false && useZ == 0 && isR9selection == true && isEPselection == false && isfbrem == false && isPtCut == false )
			name_tmp = Form ("%s_WZ_R9_EE", outputFile.c_str());
		else if(isMiscalib == false && useZ == 0 && isR9selection == false && isEPselection == false && isfbrem == true && isPtCut == false )
			name_tmp = Form ("%s_W_Fbrem_EE", outputFile.c_str());
		else if(isMiscalib == false && useZ == 0 && isR9selection == true && isEPselection == false && isfbrem == false && isPtCut == true )
			name_tmp = Form ("%s_W_PT_EE", outputFile.c_str());
		else if(isMiscalib == false && useZ == 0 && isR9selection == true && isEPselection == true && isfbrem == false && isPtCut == false )
			name_tmp = Form ("%s_W_EP_EE", outputFile.c_str());
		else if(isMiscalib == false && useZ == 0 && isEPselection == false && isR9selection == false && isPtCut == false && isfbrem == false  )
			name_tmp = Form ("%s_W_noEP_EE", outputFile.c_str());
		else {
			std::cout << " Option not considered --> exit " << std::endl;
			return -1 ;
		}

		name = Form("%s%s.root", outputPath.c_str(), name_tmp.Data());
		TFile *f1 = new TFile(name, "RECREATE");

		TString outEPDistribution = "Weight_" + name;

		TString DeadXtal = Form("%s", inputFileDeadXtal.c_str());


		if(isSaveEPDistribution == true) {
			FastCalibratorEE analyzer(tree, g_EoC_EE, typeEE, outEPDistribution);
			analyzer.bookHistos(nLoops);
			analyzer.AcquireDeadXtal(DeadXtal, isDeadTriggerTower);
			analyzer.Loop(numberOfEvents, useZ, useW, splitStat, nLoops, isMiscalib, isSaveEPDistribution, isEPselection, isR9selection, R9Min, isfbrem, fbremMax, isPtCut, PtMin, isMCTruth, jsonMap, miscalibMethod, miscalibMap);
			analyzer.saveHistos(f1);
		} else {
			FastCalibratorEE analyzer(tree, g_EoC_EE, typeEE);
			analyzer.bookHistos(nLoops);
			analyzer.AcquireDeadXtal(DeadXtal, isDeadTriggerTower);
			analyzer.Loop(numberOfEvents, useZ, useW, splitStat, nLoops, isMiscalib, isSaveEPDistribution, isEPselection, isR9selection, R9Min, isfbrem, fbremMax, isPtCut, PtMin, isMCTruth, jsonMap, miscalibMethod, miscalibMap);
			analyzer.saveHistos(f1);
		}

	}

	/// run in even-odd mode: half statistics
	else if ( splitStat == 1 ) {

		/// Prepare the outputs
		TString name;
		TString name2;

		if(isMiscalib == true && useZ == 1 && isR9selection == true && isEPselection == false && isfbrem == false && isPtCut == false) {
			name  = Form ("%s_WZ_R9_miscalib_EE_even.root", outputFile.c_str());
			name2 = Form ("%s_WZ_R9_miscalib_EE_odd.root", outputFile.c_str());
		} else if(isMiscalib == true && useZ == 1 && isR9selection == false && isEPselection == true && isfbrem == false && isPtCut == false) {
			name  = Form ("%s_WZ_EP_miscalib_EE_even.root", outputFile.c_str());
			name2 = Form ("%s_WZ_EP_miscalib_EE_odd.root", outputFile.c_str());
		} else if(isMiscalib == true && useZ == 1 && isR9selection == true && isEPselection == false && isfbrem == true && isPtCut == false) {
			name  = Form ("%s_WZ_Fbrem_miscalib_EE_even.root", outputFile.c_str());
			name2 = Form ("%s_WZ_Fbrem_miscalib_EE_odd.root", outputFile.c_str());
		} else if(isMiscalib == true && useZ == 1 && isR9selection == true && isEPselection == false && isfbrem == false && isPtCut == true) {
			name  = Form ("%s_WZ_PT_miscalib_EE_even.root", outputFile.c_str());
			name2 = Form ("%s_WZ_PT_miscalib_EE_odd.root", outputFile.c_str());
		} else if(isMiscalib == true && useZ == 1 && isR9selection == false && isEPselection == false && isfbrem == false && isPtCut == false) {
			name  = Form ("%s_WZ_noEP_miscalib_EE_even.root", outputFile.c_str());
			name2 = Form ("%s_WZ_noEP_miscalib_EE_odd.root", outputFile.c_str());
		}


		else if(isMiscalib == false && useZ == 1 && isR9selection == true && isEPselection == false && isfbrem == false && isPtCut == false) {
			name  = Form ("%s_WZ_R9_EE_even.root", outputFile.c_str());
			name2 = Form ("%s_WZ_R9_EE_odd.root", outputFile.c_str());
		} else if(isMiscalib == false && useZ == 1 && isR9selection == false && isEPselection == true && isfbrem == false && isPtCut == false) {
			name  = Form ("%s_WZ_EP_EE_even.root", outputFile.c_str());
			name2 = Form ("%s_WZ_EP_EE_odd.root", outputFile.c_str());
		} else if(isMiscalib == false && useZ == 1 && isR9selection == false && isEPselection == false && isfbrem == true && isPtCut == false) {
			name  = Form ("%s_WZ_Fbrem_EE_even.root", outputFile.c_str());
			name2 = Form ("%s_WZ_Fbrem_EE_odd.root", outputFile.c_str());
		} else if(isMiscalib == false && useZ == 1 && isR9selection == false && isEPselection == false && isfbrem == false && isPtCut == true) {
			name  = Form ("%s_WZ_PT_EE_even.root", outputFile.c_str());
			name2 = Form ("%s_WZ_PT_EE_odd.root", outputFile.c_str());
		} else if(isMiscalib == false && useZ == 1 && isR9selection == false && isEPselection == false && isfbrem == false && isPtCut == false) {
			name  = Form ("%s_WZ_noEP_EE_even.root", outputFile.c_str());
			name2 = Form ("%s_WZ_noEP_EE_odd.root", outputFile.c_str());
		}


		else if(isMiscalib == true && useZ == 0 && isR9selection == true && isEPselection == false && isfbrem == false && isPtCut == false) {
			name  = Form ("%s_W_R9_miscalib_EE_even.root", outputFile.c_str());
			name2 = Form ("%s_W_R9_miscalib_EE_odd.root", outputFile.c_str());
		}

		else if(isMiscalib == true && useZ == 0 && isR9selection == false && isEPselection == true && isfbrem == false && isPtCut == false) {
			name  = Form ("%s_W_EP_miscalib_EE_even.root", outputFile.c_str());
			name2 = Form ("%s_W_EP_miscalib_EE_odd.root", outputFile.c_str());
		} else if(isMiscalib == true && useZ == 0 && isR9selection == false && isEPselection == false && isfbrem == true && isPtCut == false) {
			name  = Form ("%s_W_Fbrem_miscalib_EE_even.root", outputFile.c_str());
			name2 = Form ("%s_W_Fbrem_miscalib_EE_odd.root", outputFile.c_str());
		} else if(isMiscalib == true && useZ == 0 && isR9selection == false && isEPselection == false && isfbrem == false && isPtCut == true) {
			name  = Form ("%s_W_PT_miscalib_EE_even.root", outputFile.c_str());
			name2 = Form ("%s_W_PT_miscalib_EE_odd.root", outputFile.c_str());
		} else if(isMiscalib == true && useZ == 0 && isR9selection == false && isEPselection == false && isfbrem == false && isPtCut == false) {
			name  = Form ("%s_W_noEP_miscalib_EE_even.root", outputFile.c_str());
			name2 = Form ("%s_W_noEP_miscalib_EE_odd.root", outputFile.c_str());
		}

		else if(isMiscalib == false && useZ == 0 && isR9selection == true && isEPselection == false && isfbrem == false && isPtCut == false) {
			name  = Form ("%s_W_R9_EE_even.root", outputFile.c_str());
			name2 = Form ("%s_W_R9_EE_odd.root", outputFile.c_str());
		}


		else if(isMiscalib == false && useZ == 0 && isR9selection == true && isEPselection == false && isfbrem == false && isPtCut == false) {
			name  = Form ("%s_W_EP_EB_even.root", outputFile.c_str());
			name2 = Form ("%s_W_EP_EB_odd.root", outputFile.c_str());
		} else if(isMiscalib == false && useZ == 0 && isR9selection == false && isEPselection == true && isfbrem == false && isPtCut == false) {
			name  = Form ("%s_W_EP_EB_even.root", outputFile.c_str());
			name2 = Form ("%s_W_EP_EB_odd.root", outputFile.c_str());
		} else if(isMiscalib == false && useZ == 0 && isR9selection == false && isEPselection == false && isfbrem == true && isPtCut == false) {
			name  = Form ("%s_W_Fbrem_EB_even.root", outputFile.c_str());
			name2 = Form ("%s_W_Fbrem_EB_odd.root", outputFile.c_str());
		} else if(isMiscalib == false && useZ == 0 && isR9selection == false && isEPselection == false && isfbrem == false && isPtCut == true) {
			name  = Form ("%s_W_PT_EB_even.root", outputFile.c_str());
			name2 = Form ("%s_W_PT_EB_odd.root", outputFile.c_str());
		} else if(isMiscalib == false && useZ == 0 && isR9selection == true && isEPselection == false && isfbrem == false && isPtCut == false) {
			name  = Form ("%s_W_noEP_EB_even.root", outputFile.c_str());
			name2 = Form ("%s_W_noEP_EB_odd.root", outputFile.c_str());
		} else {
			std::cout << " Option not considered --> exit " << std::endl;
			return -1 ;
		}

		TFile *outputName1 = new TFile(outputPath + name, "RECREATE");
		TFile *outputName2 = new TFile(outputPath + name2, "RECREATE");

		TString DeadXtal = Form("%s", inputFileDeadXtal.c_str());

		/// Run on odd
		FastCalibratorEE analyzer_even(tree, g_EoC_EE, typeEE);
		analyzer_even.bookHistos(nLoops);
		analyzer_even.AcquireDeadXtal(DeadXtal, isDeadTriggerTower);
		analyzer_even.Loop(numberOfEvents, useZ, useW, splitStat, nLoops, isMiscalib, isSaveEPDistribution, isEPselection, isR9selection, R9Min, isfbrem, fbremMax, isPtCut, PtMin, isMCTruth, jsonMap, miscalibMethod, miscalibMap);
		analyzer_even.saveHistos(outputName1);

		/// Run on even
		FastCalibratorEE analyzer_odd(tree, g_EoC_EE, typeEE);
		analyzer_odd.bookHistos(nLoops);
		analyzer_odd.AcquireDeadXtal(DeadXtal, isDeadTriggerTower);
		analyzer_odd.Loop(numberOfEvents, useZ, useW, splitStat * (-1), nLoops, isMiscalib, isSaveEPDistribution, isEPselection, isR9selection, R9Min, isfbrem, fbremMax, isPtCut, PtMin, isMCTruth, jsonMap, miscalibMethod, miscalibMap);
		analyzer_odd.saveHistos(outputName2);

	}

	delete tree;
	return 0;
}
void trisCheckCorrection_unbinnedfit(Char_t* EBEE = 0,
                         Int_t evtsPerPoint = 0,
                         float laserCorrMin = -1.,
                         float laserCorrMax = -1.)
{
  // Set style options
  gROOT->Reset();
  gROOT->SetStyle("Plain");
  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);
  gStyle->SetOptTitle(0); 
  gStyle->SetOptStat(1110); 
  gStyle->SetOptFit(1); 
  
  
  
  // Check qualifiers
  if ( strcmp(EBEE,"EB")!=0 && strcmp(EBEE,"EE")!=0 )
  {
    std::cout << "CHK-STB Error: unknown partition " << EBEE << std::endl;
    std::cout << "CHK-STB Select either EB or EE ! " << std::endl;
    return;
  }
  
  if ( strcmp(EBEE,"EB") == 0 )
  {
    lcMin = 0.99;
    lcMax = 1.05;
  }
  else
  {
    lcMin = 0.99;
    lcMax = 1.11;
  }
  
  if( (laserCorrMin != -1.) && (laserCorrMax != -1.) )
  {
    lcMin = laserCorrMin;
    lcMax = laserCorrMax;
  }
  
  
  
  // Get trees
  std::cout << std::endl;
  
  TChain* ntu_DA = new TChain("ntu");
  FillChain(ntu_DA,"inputDATA.txt");
  std::cout << "     DATA: " << std::setw(8) << ntu_DA->GetEntries() << " entries" << std::endl;
  
  TChain* ntu_MC = new TChain("ntu");
  FillChain(ntu_MC,"inputMC.txt");
  std::cout << "REFERENCE: " << std::setw(8) << ntu_MC->GetEntries() << " entries" << std::endl;
  
  if (ntu_DA->GetEntries() == 0 || ntu_MC->GetEntries() == 0 )
  {
    std::cout << "CHK-STB Error: At least one file is empty" << std::endl; 
    return;
  }  
  
  
  
  // Set branch addresses
  int runId;
  int isW, isZ;
  int timeStampHigh;
  float seedLaserAlpha;
  float avgLaserCorrection, scCrackCorrection;
  float EoP;
  float scE, scERaw, scEta, scEtaWidth, scPhiWidth;
  int seedIeta,seedIphi;
  int seedIx,seedIy,seedZside;
  float esE;
  float seedLaserCorrection;
  int iPhi,iEta;
  
  ntu_DA->SetBranchAddress("runId", &runId);  
  ntu_DA->SetBranchAddress("isW", &isW);
  //ntu_DA->SetBranchAddress("isZ", &isZ);
  ntu_DA->SetBranchAddress("timeStampHigh", &timeStampHigh);
  ntu_DA->SetBranchAddress("ele1_scCrackCorr", &scCrackCorrection);
  ntu_DA->SetBranchAddress("ele1_scLaserCorr", &avgLaserCorrection);
  ntu_DA->SetBranchAddress("ele1_seedLaserCorr", &seedLaserCorrection);
  ntu_DA->SetBranchAddress("ele1_seedLaserAlpha", &seedLaserAlpha);
  ntu_DA->SetBranchAddress("ele1_es", &esE);
  ntu_DA->SetBranchAddress("ele1_scE", &scE);
  ntu_DA->SetBranchAddress("ele1_scERaw", &scERaw);
  ntu_DA->SetBranchAddress("ele1_scEta", &scEta);
  ntu_DA->SetBranchAddress("ele1_scEtaWidth", &scEtaWidth);
  ntu_DA->SetBranchAddress("ele1_scPhiWidth", &scPhiWidth);
  ntu_DA->SetBranchAddress("ele1_EOverP", &EoP);
  ntu_DA->SetBranchAddress("ele1_seedIphi", &iPhi);
  ntu_DA->SetBranchAddress("ele1_seedIeta", &iEta);
  ntu_DA->SetBranchAddress("ele1_seedIeta",       &seedIeta);
  ntu_DA->SetBranchAddress("ele1_seedIphi",       &seedIphi);
  ntu_DA->SetBranchAddress("ele1_seedIx",         &seedIx);
  ntu_DA->SetBranchAddress("ele1_seedIy",         &seedIy);
  ntu_DA->SetBranchAddress("ele1_seedZside",      &seedZside);
  
  ntu_MC->SetBranchAddress("isW", &isW);
  ntu_MC->SetBranchAddress("isZ", &isZ);
  ntu_MC->SetBranchAddress("ele1_scEta", &scEta);
  ntu_MC->SetBranchAddress("ele1_EOverP", &EoP);
  
  

  float params[42];
  InitializeParams(params);
  
  
  // Build the reference from 'infile2'
  std::cout << std::endl;
  std::cout << "***** Build reference for " << EBEE << " *****" << std::endl;
  
  templateHisto = new TH1F("templateHisto", "", 1200, 0., 5.);

  for(int ientry = 0; ientry < ntu_MC->GetEntries(); ++ientry)
  {
    if( (ientry%100000 == 0) ) std::cout << "reading MC entry " << ientry << std::endl;
    ntu_MC->GetEntry(ientry);
    
    if (strcmp(EBEE,"EB")==0 && fabs(scEta) > 1.4442) continue;                       // barrel
    if (strcmp(EBEE,"EE")==0 && (fabs(scEta) < 1.56 || fabs(scEta) > 2.5 )) continue; // endcap
    
    //if( seedLaserAlpha > 1.5 ) continue;
        
    //if( fabs(scEta) > 0.44 ) continue;
    //if( fabs(scEta) < 0.44 || fabs(scEta) > 0.77 ) continue;
    //if( fabs(scEta) < 0.77 || fabs(scEta) > 1.10 ) continue;
    //if( fabs(scEta) < 1.10 || fabs(scEta) > 1.56 ) continue;
    //if( fabs(scEta) < 1.56 || fabs(scEta) > 2.00 ) continue;
    //if( fabs(scEta) < 2.00 ) continue;
        
    templateHisto -> Fill(EoP);
  }

  int rebin = 4;
  if (strcmp(EBEE,"EB")==0) rebin = 2;
  templateHisto -> Rebin(rebin);  
  FitTemplate();
  
  std::cout << "Reference built for " << EBEE << " - " << templateHisto->GetEntries() << " events" << std::endl;
  
  
  
  // Loop and sort events
  std::cout << std::endl;
  std::cout << "***** Sort events and define bins *****" << std::endl;
  
  int nEntries = ntu_DA -> GetEntriesFast(); 
  int nSavePts = 0; 
  std::vector<bool> isSavedEntries(nEntries);
  std::vector<SorterLC> sortedEntries;
  
  for(int ientry = 0; ientry < nEntries; ++ientry)
  {
    ntu_DA -> GetEntry(ientry); 
    isSavedEntries.at(ientry) = false;
    
    // save only what is needed for the analysis!!!
    if (strcmp(EBEE,"EB")==0 && fabs(scEta) > 1.4442) continue;                       // barrel
    if (strcmp(EBEE,"EE")==0 && (fabs(scEta) < 1.56 || fabs(scEta) > 2.5 )) continue; // endcap
    
    //if( fabs(scEta) > 0.44 ) continue;
    //if( fabs(scEta) < 0.44 || fabs(scEta) > 0.77 ) continue;
    //if( fabs(scEta) < 0.77 || fabs(scEta) > 1.10 ) continue;
    //if( fabs(scEta) < 1.10 || fabs(scEta) > 1.56 ) continue;
    //if( fabs(scEta) < 1.56 || fabs(scEta) > 2.00 ) continue;
    //if( fabs(scEta) < 2.00 ) continue;
    
        
    if( seedLaserCorrection <= 1.) continue;   
    if( seedLaserAlpha < 1.5 ) continue;
    //if( timeStampHigh > 1303862400 ) continue;
    
    if( seedZside < 0 )
      if( (seedIx > 20 ) && (seedIx < 50) && (seedIy > 85) && (seedIy < 92) ) continue;
    if( seedZside == -1 )
      if( (seedIx > 35 ) && (seedIx < 55) && (seedIy > 80) && (seedIy < 87) ) continue;
    if( seedZside > 0 )
      if( (seedIx > 65 ) && (seedIx < 77) && (seedIy > 33) && (seedIy < 57) ) continue;
    if( seedZside > 0 )
      if( (seedIx > 75 ) && (seedIx < 93) && (seedIy > 18) && (seedIy < 37) ) continue;    
    
    //if ( runId < 163045 ) continue;
    //if ( runId >= 163232 ) continue;
    //if ( runId < 163232 ) continue;
    
    
    //*********************** CLUSTER CORR *****************************
    //if( (ientry%1 == 0) ) std::cout << "\n\n\nreading entry " << ientry << std::endl;    
    //Ediff -> Fill( ( (scCrackCorrection*fClusterCorrections(scERaw+esE,scEta,scPhiWidth/scEtaWidth,params))-scE)/scE );
    //Ediff_vsEta -> Fill( scEta, ( (esE+scCrackCorrection*fClusterCorrections(scERaw,scEta,scPhiWidth/scEtaWidth,params))-scE)/scE );
    //if( fabs(fClusterCorrections(scERaw,scEta,scPhiWidth/scEtaWidth,params)-scE) > 0.001 )
    //{
    //  std::cout << "\n\n" << std::endl;
    //  std::cout << "scEta = " << scEta << "   scE = " << scE << "   scERaw = " << scERaw << std::endl;
    //  std::cout << "scERaw_corr = " << fClusterCorrections(scERaw,scEta,scPhiWidth/scEtaWidth,params) << std::endl;
    //}
    //*********************** CLUSTER CORR *****************************
        
    isSavedEntries.at(ientry) = true;
    
    SorterLC dummy;
    dummy.laserCorr = avgLaserCorrection;
    dummy.entry = ientry;
    sortedEntries.push_back(dummy);
    
    nSavePts++; 
  }
  std::sort(sortedEntries.begin(),sortedEntries.end(),SorterLC());
  std::cout << "Data sorted in " << EBEE << " - " << nSavePts << " events" << std::endl;
  
  //TCanvas* c_diff = new TCanvas("c_diff","c_diff");
  //c_diff -> cd();
  //Ediff -> Draw();
  //
  //TCanvas* c_diff_vsEta = new TCanvas("c_diff_vsEta","c_diff");
  //c_diff_vsEta -> cd();
  //Ediff_vsEta -> Draw("colz");
  
  // bins with evtsPerPoint events per bin
  int nBins = std::max(1,int(nSavePts/evtsPerPoint));
  int nBinPts = int( nSavePts/nBins );
  int nBinTempPts = 0;
  
  std::vector<int> binEntryMax;
  binEntryMax.push_back(0);
  for(int iSaved = 0; iSaved < nSavePts; ++iSaved)
  {
    ++nBinTempPts;
    
    if( nBinTempPts == nBinPts )
    {
      binEntryMax.push_back( iSaved );      
      nBinTempPts = 0;
    }
  }
  binEntryMax.at(nBins) = nSavePts;
  
  std::cout << "nBins = " << nBins << std::endl;
  for(int bin = 0; bin < nBins; ++bin)
    std::cout << "bin: " << bin
              << "   entry min: " << setw(6) << binEntryMax.at(bin)
              << "   entry max: " << setw(6) << binEntryMax.at(bin+1)
              << "   events: "    << setw(6) << binEntryMax.at(bin+1)-binEntryMax.at(bin)
              << std::endl;
  TVirtualFitter::SetDefaultFitter("Fumili2");
  
  
  
  // histogram definition
  
  TH1F* h_EoP_spread;
  TH1F* h_EoC_spread;
  TH2F* h_LC_map = new TH2F("h_LC_map","",360,0.,360,170,-85,85);
  
  if ( strcmp(EBEE,"EB")==0 )
  {  
    h_EoP_spread = new TH1F("h_EoP_spread","",100,0.95,1.01);
    h_EoC_spread = new TH1F("h_EoC_spread","",100,0.95,1.01);    
  }
  else 
  {  
    h_EoP_spread = new TH1F("h_EoP_spread","",100,0.91,1.03);
    h_EoC_spread = new TH1F("h_EoC_spread","",100,0.91,1.03);    
  }
  
  h_EoP_spread -> SetLineColor(kRed+2);
  h_EoP_spread -> SetLineWidth(2);
  h_EoP_spread -> GetXaxis() -> SetTitle("Relative E/p scale");

  h_EoC_spread -> SetLineColor(kGreen+2);
  h_EoC_spread -> SetLineWidth(2);
  h_EoC_spread -> GetXaxis() -> SetTitle("Relative E/p scale");  
  
  
  TH1F** h_EoP = new TH1F*[nBins];
  TH1F** h_EoC = new TH1F*[nBins];
  TH1F** h_Las = new TH1F*[nBins];

  for(int i = 0; i < nBins; ++i)
  {
    char histoName[80];
    
    sprintf(histoName, "EoP_%d", i);
    h_EoP[i] = new TH1F(histoName, histoName, 1200, 0., 3.);
    h_EoP[i] -> SetFillColor(kRed+2);
    h_EoP[i] -> SetFillStyle(3004);
    h_EoP[i] -> SetMarkerStyle(7);
    h_EoP[i] -> SetMarkerColor(kRed+2); 
    h_EoP[i] -> SetLineColor(kRed+2); 
    
    sprintf(histoName, "EoC_%d", i);
    h_EoC[i] = new TH1F(histoName, histoName, 1200, 0., 3.);
    h_EoC[i] -> SetFillColor(kGreen+2);
    h_EoC[i] -> SetFillStyle(3004);
    h_EoC[i] -> SetMarkerStyle(7);
    h_EoC[i] -> SetMarkerColor(kGreen+2);
    h_EoC[i] -> SetLineColor(kGreen+2);
    
    sprintf(histoName, "Las_%d", i);
    h_Las[i] = new TH1F(histoName, histoName, 100, 0.5, 1.5);
  }
  
  
  // data definition
  std::vector< std::vector<double>* > dataEoP;
  std::vector< std::vector<double>* > dataEoC;
  
  for (int jbin = 0; jbin< nBins; jbin++){
    dataEoP.push_back(new std::vector<double>);
    dataEoC.push_back(new std::vector<double>);
  }


  // function definition
  TF1** f_EoP = new TF1*[nBins];
  TF1** f_EoC = new TF1*[nBins];
  
  
    
  // loop on the saved and sorted events
  std::cout << std::endl;
  std::cout << "***** Fill and fit histograms *****" << std::endl;

  
  for(int ientry = 0; ientry < nEntries; ++ientry)
  {
    if( (ientry%10000 == 0) ) std::cout << "reading entry " << ientry << std::endl;
    
    if( isSavedEntries.at(ientry) == false ) continue;
    
    int iSaved = -1;
    for(iSaved = 0; iSaved < nSavePts; ++iSaved)
      if( ientry == sortedEntries[iSaved].entry ) break;
    
    int bin = -1;
    for(bin = 0; bin < nBins; ++bin)
      if( iSaved >= binEntryMax.at(bin) && iSaved < binEntryMax.at(bin+1) )
        break;
    
    //std::cout << "ientry = " << ientry << "   iSaved: " << iSaved << "   bin: " << bin << std::endl;
    
    ntu_DA->GetEntry(ientry);
    
    float scale = 1.;
    //scale = sqrt( pow(avgLaserCorrection,((1.52-0.7843)/1.52)-1.) );
    //scale = 1. / (0.1811 + 0.7843*avgLaserCorrection);
    
        
    //// fill the bins 
    (h_Las[bin]) -> Fill(avgLaserCorrection);
    (h_EoP[bin]) -> Fill(EoP/avgLaserCorrection);
    (h_EoC[bin]) -> Fill(EoP * scale);
    h_LC_map->Fill(iPhi,iEta,seedLaserCorrection);

    // fill te vectors data E/p 
    dataEoP[bin]->push_back(EoP/avgLaserCorrection);
    dataEoC[bin]->push_back(EoP);

  }
  

  // Define graph and histograms
  TGraphAsymmErrors* g_fit   = new TGraphAsymmErrors();
  TGraphAsymmErrors* g_c_fit   = new TGraphAsymmErrors();
  
  
  
  // define the fitting function
  // N.B. [0] * ( [1] * f( [1]*(x-[2]) ) )
  histoFunc* templateHistoFunc = new histoFunc(templateHisto);
   
  //templateFunc = new TF1("templateFunc", templateHistoFunc, 0., 5., 3, "histoFunc");
  //templateFunc -> SetParName(0,"Norm"); 
  //templateFunc -> SetParName(1,"Scale factor"); 
  //templateFunc -> SetLineWidth(1); 
  //templateFunc -> SetNpx(10000);
  //templateFunc -> SetParameter(0, 1 );
  //templateFunc -> SetParameter(1, 1);
  //templateFunc -> FixParameter(2, 0.);
  //templateFunc -> FixParameter(0, 1./templateFunc ->Integral(0.,5.) ); // normalized to 1. BUT will be renormalized to 1 at each iteration!
  
  TFitterMinuit* myfit = new TFitterMinuit(1);
  myfit->SetFCN(mylike);
  myfit->SetPrintLevel(-1);
  
  
  
  for(int i = 0; i < nBins; ++i)
  {
    h_EoP[i] -> Rebin(rebin*4);    
    h_EoC[i] -> Rebin(rebin*4);    
    
    
    //------------------------------------
    // Fill the graph for uncorrected data
    
    // fit uncorrected data
    mydata = dataEoP.at(i);
    
    myfit->Clear();
    myfit->SetParameter(0, "scale", 1.,0.0005,0.50,1.50);
    
    double arglist[2];
    arglist[0] = 10000; // Max number of function calls
    arglist[1] = 1e-5;  // Tolerance on likelihood ?????????

    int fStatus = myfit->ExecuteCommand("MIGRAD",arglist,2); 
    
    double amin,edm,errdef;
    int nvpar,nparx;
    myfit->GetStats(amin, edm, errdef, nvpar, nparx);
    double bestScale = myfit->GetParameter(0);
    double eee       = myfit->GetParError(0);
    
    char funcName[50];
    sprintf(funcName,"f_EoP_%d",i);
    f_EoP[i] = (TF1*)(templateFunc->Clone());
    f_EoP[i] -> SetParameter(0,h_EoP[i]->GetEntries());
    f_EoP[i] -> SetParameter(7,1.5);
    f_EoP[i] -> SetParName(0,"Norm"); 
    f_EoP[i] -> SetParName(1,"Scale factor"); 
    f_EoP[i] -> SetLineWidth(1); 
    f_EoP[i] -> SetNpx(10000);
    
    double xNorm = h_EoP[i]->GetEntries()/templateHisto->GetEntries() *
                   h_EoP[i]->GetBinWidth(1)/templateHisto->GetBinWidth(1); 
    
    //f_EoP[i] -> FixParameter(0, xNorm);
    //f_EoP[i] -> SetParameter(1, bestScale);
    //f_EoP[i] -> FixParameter(2, 0.);
    f_EoP[i] -> SetLineColor(kRed+2); 
    
    // Fill the graph
    if( fStatus == 0 && eee > 0. )
    {
      g_fit -> SetPoint(i,  h_Las[i]->GetMean() , 1./bestScale);
      g_fit -> SetPointError(i, h_Las[i]->GetRMS(), h_Las[i]->GetRMS(), eee, eee);
      h_EoP_spread -> Fill(1./bestScale);
    }
    else
      std::cout << "Fitting uncorrected time bin: " << i << "   Fail status: " << fStatus << "   sigma: " << eee << endl;
    
    
    
    //----------------------------------
    // Fill the graph for corrected data

    // fit uncorrected data
    
    mydata = dataEoC.at(i);
    
    myfit->Clear();
    myfit->SetParameter(0, "scale", 1.,0.0005,0.50,1.50);
    
    arglist[0] = 10000; // Max number of function calls
    arglist[1] = 1e-5;  // Tolerance on likelihood ?????????

    fStatus = myfit->ExecuteCommand("MIGRAD",arglist,2); 
    
    myfit->GetStats(amin, edm, errdef, nvpar, nparx);
    bestScale = myfit->GetParameter(0);
    eee       = myfit->GetParError(0);    
    
    
    sprintf(funcName,"f_EoC_%d",i);
    f_EoC[i] = (TF1*)(templateFunc->Clone());
    f_EoC[i] -> SetParameter(0,h_EoC[i]->GetEntries());
    f_EoC[i] -> SetParameter(7,bestScale);
    f_EoC[i] -> SetParName(0,"Norm"); 
    f_EoC[i] -> SetParName(1,"Scale factor"); 
    f_EoC[i] -> SetLineWidth(1); 
    f_EoC[i] -> SetNpx(10000);

    xNorm = h_EoC[i]->GetEntries()/templateHisto->GetEntries() *
            h_EoC[i]->GetBinWidth(1)/templateHisto->GetBinWidth(1); 
    //
    //f_EoC[i] -> SetParameter(1, bestScale);
    //f_EoC[i] -> FixParameter(2, 0.);
    f_EoC[i] -> SetLineColor(kGreen+2); 

    // fill the graph
    if( fStatus == 0 && eee > 0. )
    {        
      g_c_fit -> SetPoint(i,  h_Las[i]->GetMean() , 1./bestScale);
      g_c_fit -> SetPointError(i, h_Las[i]->GetRMS() , h_Las[i]->GetRMS() , eee, eee);
      h_EoC_spread -> Fill(1./bestScale);
    }
    else 
      std::cout << "Fitting corrected time bin: " << i << "   Fail status: " << fStatus << "   sigma: " << eee << endl;
    
    
    
  }
  
  TF1* pol0 = new TF1("pol0","pol0");
  pol0 -> SetLineColor(kGreen+2);
  pol0 -> SetLineWidth(3);
  pol0 -> SetLineStyle(2);
  g_c_fit -> Fit("pol0","Q+");
  
  
  // Drawings
  TPaveStats** s_EoP = new TPaveStats*[nBins];
  TPaveStats** s_EoC = new TPaveStats*[nBins];
  
  TCanvas *c1[100]; 
  for(int i = 0; i < nBins; ++i)
  {
    char canvasName[50];
    if (i%2==0) {
      sprintf(canvasName, "Fits-%0d", i/2); 
      c1[i/2] = new TCanvas(canvasName, canvasName);
      c1[i/2] -> Divide(2,1);
    }
    c1[i/2] -> cd (i%2+1);

    h_EoP[i] -> GetXaxis() -> SetTitle("E/p");  
    h_EoP[i] -> GetXaxis() -> SetRangeUser(0.5,1.5); 
    h_EoP[i] -> Draw("e");
    gPad->Update();
    s_EoP[i]= (TPaveStats*)(h_EoP[i]->GetListOfFunctions()->FindObject("stats"));
    s_EoP[i]->SetTextColor(kRed+2);

    h_EoC[i] -> Draw("esames");
    gPad->Update(); 
    s_EoC[i]= (TPaveStats*)(h_EoC[i]->GetListOfFunctions()->FindObject("stats"));
    s_EoC[i]->SetY1NDC(0.59); //new x start position
    s_EoC[i]->SetY2NDC(0.79); //new x end position
    s_EoC[i]->SetTextColor(kGreen+2);
    s_EoC[i]->Draw();
    
    f_EoP[i]->Draw("same");
    f_EoC[i]->Draw("same");    
  }

  /*  
  TCanvas *c2[100]; 
  for(int i = 0; i < nBins; ++i)
  {
    char canvasName[50];
    if (i%6==0) {
      sprintf(canvasName, "LaserCorr-%0d", i/6); 
      c2[i/6] = new TCanvas(canvasName, canvasName);
      c2[i/6] -> Divide(3,2);
    }
        
    c2[i/6] -> cd (i%6+1);
    h_Las[i] -> GetXaxis() -> SetTitle("laser correction");
    h_Las[i] -> GetXaxis() -> SetRangeUser(0.5,1.5); 
    h_Las[i] -> Draw("");
    gPad->Update();
    s_Las[i]= (TPaveStats*)(h_Las[i]->GetListOfFunctions()->FindObject("stats"));
    s_Las[i]->SetTextColor(kBlack);
  }
  */

  /*  
  TCanvas *cmap = new TCanvas("cmap","cmap");
  cmap->cd();
  gStyle->SetPalette(1);
  h_LC_map->Draw("colz");
  */
  
  // Final plots
  TCanvas* cplot = new TCanvas("gplot", "gplot",100,100,725,500);
  cplot->cd();

  TPad *cLeft  = new TPad("pad_0","pad_0",0.00,0.00,0.64,1.00);
  TPad *cRight = new TPad("pad_1","pad_1",0.64,0.00,1.00,1.00);

  cLeft->SetLeftMargin(0.15); 
  cLeft->SetRightMargin(0.025); 
  cRight->SetLeftMargin(0.025); 

  cLeft->Draw();
  cRight->Draw();

  float tYoffset = 1.5; 
  float labSize = 0.04;
  float labSize2 = 0.07;

  cLeft->cd(); 

  cLeft->SetGridx();
  cLeft->SetGridy();
  
  // pad settings
  TH1F *hPad = (TH1F*)gPad->DrawFrame(lcMin,0.9,lcMax,1.05);
  hPad->GetXaxis()->SetTitle("Laser correction");
  hPad->GetYaxis()->SetTitle("Relative E/p scale"); 
  hPad->GetYaxis()->SetTitleOffset(tYoffset);
  hPad->GetXaxis()->SetLabelSize(labSize);
  hPad->GetXaxis()->SetTitleSize(labSize);
  hPad->GetYaxis()->SetLabelSize(labSize);
  hPad->GetYaxis()->SetTitleSize(labSize);
  if ( strcmp(EBEE,"EB")==0 )
  {  
    hPad -> SetMinimum(0.950);
    hPad -> SetMaximum(1.010);
  }
  else 
  {  
    hPad -> SetMinimum(0.910);
    hPad -> SetMaximum(1.030);
  }
    
  // draw trend plot
  g_fit -> SetMarkerStyle(20);
  g_fit -> SetMarkerSize(0.75);
  g_fit -> SetMarkerColor(kRed+2);
  g_fit -> SetLineColor(kRed+2);
  g_fit -> Draw("P");
  g_c_fit -> SetMarkerStyle(20);
  g_c_fit -> SetMarkerColor(kGreen+2);
  g_c_fit -> SetLineColor(kGreen+2);
  g_c_fit -> SetMarkerSize(0.75);
  g_c_fit -> Draw("P,same");
  
  
  cRight -> cd();

  TPaveStats* s_EoP_spread = new TPaveStats();
  TPaveStats* s_EoC_spread = new TPaveStats();
  
  h_EoC_spread -> SetFillStyle(3001);
  h_EoC_spread -> SetFillColor(kGreen+2);
  h_EoC_spread->GetYaxis()->SetLabelSize(labSize2);
  h_EoC_spread->GetYaxis()->SetTitleSize(labSize2);
  h_EoC_spread->GetYaxis()->SetNdivisions(505);
  h_EoC_spread->GetYaxis()->SetLabelOffset(-0.02);
  h_EoC_spread->GetXaxis()->SetLabelOffset(1000);

  h_EoC_spread -> Draw("hbar");
  gPad -> Update();
  s_EoC_spread = (TPaveStats*)(h_EoC_spread->GetListOfFunctions()->FindObject("stats"));
  s_EoC_spread ->SetTextColor(kGreen+2);
  s_EoC_spread ->SetTextSize(0.06);
  s_EoC_spread->SetX1NDC(0.49); //new x start position
  s_EoC_spread->SetX2NDC(0.99); //new x end position
  s_EoC_spread->SetY1NDC(0.875); //new x start position
  s_EoC_spread->SetY2NDC(0.990); //new x end position
  s_EoC_spread -> SetOptStat(1100);
  s_EoC_spread -> Draw("sames");

  h_EoP_spread -> SetFillStyle(3001);
  h_EoP_spread -> SetFillColor(kRed+2);
  h_EoP_spread -> Draw("hbarsames");
  gPad -> Update();
  s_EoP_spread = (TPaveStats*)(h_EoP_spread->GetListOfFunctions()->FindObject("stats"));
  s_EoP_spread->SetX1NDC(0.49); //new x start position
  s_EoP_spread->SetX2NDC(0.99); //new x end position
  s_EoP_spread->SetY1NDC(0.750); //new x start position
  s_EoP_spread->SetY2NDC(0.875); //new x end position
  s_EoP_spread ->SetOptStat(1100);
  s_EoP_spread ->SetTextColor(kRed+2);
  s_EoP_spread ->SetTextSize(0.06);
  s_EoP_spread -> Draw("sames");
}
Esempio n. 8
0
int main(int argc, char** argv)
{
  //Check if all nedeed arguments to parse are there
  if(argc != 2)
  {
    std::cerr << ">>> drawNVtx::usage: " << argv[0] << " configFileName" << std::endl;
    return -1;
  }
  
  
  
  //----------------------
  // Parse the config file
  
  parseConfigFile(argv[1]);
  
  std::string inputFilesDA = gConfigParser -> readStringOption("Input::inputFilesDA");
  std::string inputFilesMC = gConfigParser -> readStringOption("Input::inputFilesMC");
  
  extension  = gConfigParser -> readStringOption("Options::extension");
  int maxEntries = gConfigParser -> readIntOption("Options::maxEntries");
  std::string dataLabel = gConfigParser -> readStringOption("Options::dataLabel");
  
  std::string outFilePath = gConfigParser -> readStringOption("Output::outFilePath");
  
  
  
  //------------------
  // Set style options
  
  setTDRStyle();
  gStyle->SetPadTopMargin(0.05);
  gStyle->SetPadBottomMargin(0.13);
  gStyle->SetPadLeftMargin(0.13);
  gStyle->SetPadRightMargin(0.17);
  gStyle->SetLabelSize(0.04,"XYZ");
  gStyle->SetTitleSize(0.05,"XYZ");
  gStyle->SetOptStat(0);
  gStyle->SetOptFit(0);
  
  
  
  //----------
  // Get trees
  
  std::cout << std::endl;
  
  TChain* ntu_MC = new TChain("selected");
  FillChain(ntu_MC,inputFilesMC);
  std::cout << ">>>   MC: " << std::setw(8) << ntu_MC->GetEntries() << " entries" << std::endl;
  
  TChain* ntu_DA = new TChain("selected");
  FillChain(ntu_DA,inputFilesDA);
  std::cout << ">>> DATA: " << std::setw(8) << ntu_DA->GetEntries() << " entries" << std::endl;
  
  if( ntu_MC->GetEntries() == 0 || ntu_DA->GetEntries() == 0 )
  {
    std::cout << ">>> drawNVtx::Error: at least one file is empty" << std::endl; 
    return -1;
  }
  
  
  
  //---------------------
  // Set branch addresses
  
  int runId;
  int nPV;
  int nPU;
  bool HLTfire;
  int* eleID = new int[2];
   
  ntu_DA -> SetBranchStatus("*",0);
  ntu_DA -> SetBranchStatus("runNumber",1); ntu_DA -> SetBranchAddress("runNumber",&runId);
  ntu_DA -> SetBranchStatus("nPV",      1); ntu_DA -> SetBranchAddress("nPV",      &nPV);
  ntu_DA -> SetBranchStatus("HLTfire",  1); ntu_DA -> SetBranchAddress("HLTfire",  &HLTfire);
  ntu_DA -> SetBranchStatus("eleID",    1); ntu_DA -> SetBranchAddress("eleID",    eleID);
  
  ntu_MC -> SetBranchStatus("runNumber",1); ntu_MC -> SetBranchAddress("runNumber",&runId);
  ntu_MC -> SetBranchStatus("nPV",      1); ntu_MC -> SetBranchAddress("nPV",      &nPV);  
  ntu_MC -> SetBranchStatus("nPU",      1); ntu_MC -> SetBranchAddress("nPU",      &nPU);  
  ntu_MC -> SetBranchStatus("HLTfire",  1); ntu_MC -> SetBranchAddress("HLTfire",  &HLTfire);
  ntu_MC -> SetBranchStatus("eleID",    1); ntu_MC -> SetBranchAddress("eleID",    eleID);
  
  
  // Define histograms
  std::vector<std::string> categories;
  
  categories.push_back("all");
  categories.push_back("all_HLTfire");
  categories.push_back("all_HLTfire_eleID");
  categories.push_back("all_noPUWeight");
  categories.push_back("Run2012AB");
  categories.push_back("Run2012AB_HLTfire");
  categories.push_back("Run2012AB_HLTfire_eleID");
  categories.push_back("Run2012AB_noPUWeight");
  categories.push_back("Run2012C");
  categories.push_back("Run2012C_HLTfire");
  categories.push_back("Run2012C_HLTfire_eleID");
  categories.push_back("Run2012C_noPUWeight");
  categories.push_back("Run2012D");
  categories.push_back("Run2012D_HLTfire");
  categories.push_back("Run2012D_HLTfire_eleID");
  categories.push_back("Run2012D_noPUWeight");
  
  for(unsigned int i = 0; i < categories.size(); ++i)
  {
    std::string category = categories.at(i);
    
    std::string histoName = "h_nPV_MC_"+category;
    h_nPV_MC[category] = new TH1F(histoName.c_str(),"",50,0.5,50.5);
    h_nPV_MC[category] -> Sumw2();
    
    histoName = "h_nPV_DA_"+category;
    h_nPV_DA[category] = new TH1F(histoName.c_str(),"",50,0.5,50.5);
    h_nPV_DA[category] -> Sumw2();
  }
  
  
  
  // define arrays for KS test
  std::map<std::string,std::vector<double> > masses;
  std::map<std::string,std::map<double,std::vector<double> > > masses_c;
  
  
  
  // pileup reweighting for MC
  std::map<std::string, std::map<float,float> > PUWeights;
  std::string PUDir(getenv("COMMONUTILS"));
  
  if( dataLabel == "Winter2013" )
  {
    PUWeights["Run2012AB"] = *(ComputePUWeights((PUDir+"/data/pileup/PUWeights_DYToEE_M20_powheg-Summer12-START53-ZSkim-runDependent_Run2012AB.root").c_str(),"h_PUweights",false));
    PUWeights["Run2012C"]  = *(ComputePUWeights((PUDir+"/data/pileup/PUWeights_DYToEE_M20_powheg-Summer12-START53-ZSkim-runDependent_Run2012C.root").c_str(), "h_PUweights",false));
    PUWeights["Run2012D"]  = *(ComputePUWeights((PUDir+"/data/pileup/PUWeights_DYToEE_M20_powheg-Summer12-START53-ZSkim-runDependent_Run2012D.root").c_str(), "h_PUweights",false));
  }
  
  
  
  // Loop over entries
  std::cout << std::endl;
  std::cout << ">>> Read data from MC sample" << std::endl;
  
  int nEntries_MC = ntu_MC -> GetEntriesFast();
  for(int ientry = 0; ientry < nEntries_MC; ++ientry)
  {
    if( maxEntries != -1 && ientry == maxEntries ) break;
    if( ientry%100000 == 0 ) std::cout << ">>>>>> reading   MC entry " << ientry << " / " << nEntries_MC << "\r"<< std::flush;
    ntu_MC -> GetEntry(ientry);
    
    
    // variables
    std::string runLabel = GetRunLabel(runId);
    float ww = (PUWeights[runLabel])[int(nPU+0.5)];
    bool passEleID = false;
    if( ((eleID[0] & 6) == 6) && ((eleID[1] & 6) == 6) ) passEleID = true;
    
    
    // selections
    //if( isZ != 1 ) continue;
    
    
    // fill histograms
    h_nPV_MC["all"]             ->  Fill( nPV,ww );
    if( HLTfire ) h_nPV_MC["all_HLTfire"]     ->  Fill( nPV,ww );
    if( HLTfire && passEleID ) h_nPV_MC["all_HLTfire_eleID"]     ->  Fill( nPV,ww );
    h_nPV_MC["all_noPUWeight"]  ->  Fill( nPV,1. );
    
    if( runLabel == "Run2012AB" )
    {
      h_nPV_MC["Run2012AB"]             ->  Fill( nPV,ww );
      if( HLTfire ) h_nPV_MC["Run2012AB_HLTfire"]     ->  Fill( nPV,ww );
      if( HLTfire && passEleID ) h_nPV_MC["Run2012AB_HLTfire_eleID"]     ->  Fill( nPV,ww );
      h_nPV_MC["Run2012AB_noPUWeight"]  ->  Fill( nPV,1. );
    }
    
    if( runLabel == "Run2012C" )
    {
      h_nPV_MC["Run2012C"]             ->  Fill( nPV,ww );
      if( HLTfire ) h_nPV_MC["Run2012C_HLTfire"]     ->  Fill( nPV,ww );
      if( HLTfire && passEleID ) h_nPV_MC["Run2012C_HLTfire_eleID"]     ->  Fill( nPV,ww );
      h_nPV_MC["Run2012C_noPUWeight"]  ->  Fill( nPV,1. );
    }
    
    if( runLabel == "Run2012D" )
    {
      h_nPV_MC["Run2012D"]             ->  Fill( nPV,ww );
      if( HLTfire ) h_nPV_MC["Run2012D_HLTfire"]     ->  Fill( nPV,ww );
      if( HLTfire && passEleID ) h_nPV_MC["Run2012D_HLTfire_eleID"]     ->  Fill( nPV,ww );
      h_nPV_MC["Run2012D_noPUWeight"]  ->  Fill( nPV,1. );
    }
  }
  std::cout << std::endl;
  
  
  int nEntries_DA = ntu_DA -> GetEntriesFast();
  for(int ientry = 0; ientry < nEntries_DA; ++ientry)
  {
    if( maxEntries != -1 && ientry == maxEntries ) break;
    if( ientry%100000 == 0 ) std::cout << ">>>>>> reading   DA entry " << ientry << " / " << nEntries_DA << "\r"<< std::flush;
    ntu_DA -> GetEntry(ientry);
    
    
    // variables
    std::string runLabel = GetRunLabel(runId);
    float ww = 1.;
    bool passEleID = false;
    if( ((eleID[0] & 6) == 6) && ((eleID[1] & 6) == 6) ) passEleID = true;
    
    
    // selections
    //if( isZ != 1 ) continue;
    
    
    // fill histograms
    h_nPV_DA["all"]             ->  Fill( nPV,ww );
    if( HLTfire ) h_nPV_DA["all_HLTfire"]     ->  Fill( nPV,ww );
    if( HLTfire && passEleID ) h_nPV_DA["all_HLTfire_eleID"]     ->  Fill( nPV,ww );
    h_nPV_DA["all_noPUWeight"]  ->  Fill( nPV,1. );
    
    if( runLabel == "Run2012AB" )
    {
      h_nPV_DA["Run2012AB"]             ->  Fill( nPV,ww );
      if( HLTfire ) h_nPV_DA["Run2012AB_HLTfire"]     ->  Fill( nPV,ww );
      if( HLTfire && passEleID ) h_nPV_DA["Run2012AB_HLTfire_eleID"]     ->  Fill( nPV,ww );
      h_nPV_DA["Run2012AB_noPUWeight"]  ->  Fill( nPV,1. );
    }
    
    if( runLabel == "Run2012C" )
    {
      h_nPV_DA["Run2012C"]             ->  Fill( nPV,ww );
      if( HLTfire ) h_nPV_DA["Run2012C_HLTfire"]     ->  Fill( nPV,ww );
      if( HLTfire && passEleID ) h_nPV_DA["Run2012C_HLTfire_eleID"]     ->  Fill( nPV,ww );
      h_nPV_DA["Run2012C_noPUWeight"]  ->  Fill( nPV,1. );
    }
    
    if( runLabel == "Run2012D" )
    {
      h_nPV_DA["Run2012D"]             ->  Fill( nPV,ww );
      if( HLTfire ) h_nPV_DA["Run2012D_HLTfire"]     ->  Fill( nPV,ww );
      if( HLTfire && passEleID ) h_nPV_DA["Run2012D_HLTfire_eleID"]     ->  Fill( nPV,ww );
      h_nPV_DA["Run2012D_noPUWeight"]  ->  Fill( nPV,1. );
    }
  }
  std::cout << std::endl;
  
  
  
  // Drawings
  std::string folderName = outFilePath + "/" + dataLabel + "/";
  gSystem -> mkdir(folderName.c_str());
  
  std::string outFileName = folderName + "/drawNVtx";
  outFile = new TFile((outFileName+".root").c_str(),"RECREATE");
  
  TCanvas* dummy = new TCanvas("dummy","",0,0,700,600);
  dummy -> Print((outFileName+"."+extension+"[").c_str(),extension.c_str());
  
  DrawNVtx("all",              "[Run2012ABCD]",                 1,outFileName);
  DrawNVtx("all_HLTfire",      "[Run2012ABCD - with HLT]",      1,outFileName);
  DrawNVtx("all_HLTfire_eleID","[Run2012ABCD - with HLT+eleID]",1,outFileName);
  DrawNVtx("all_noPUWeight",   "[Run2012ABCD - no PU reweigh.]",1,outFileName);
  
  DrawNVtx("Run2012AB",              "[Run2012AB]",                 1,outFileName);
  DrawNVtx("Run2012AB_HLTfire",      "[Run2012AB - with HLT]",      1,outFileName);
  DrawNVtx("Run2012AB_HLTfire_eleID","[Run2012AB - with HLT+eleID]",1,outFileName);
  DrawNVtx("Run2012AB_noPUWeight",   "[Run2012AB - no PU reweigh.]",1,outFileName);
  
  DrawNVtx("Run2012C",              "[Run2012C]",                 1,outFileName);
  DrawNVtx("Run2012C_HLTfire",      "[Run2012C - with HLT]",      1,outFileName);
  DrawNVtx("Run2012C_HLTfire_eleID","[Run2012C - with HLT+eleID]",1,outFileName);
  DrawNVtx("Run2012C_noPUWeight",   "[Run2012C - no PU reweigh.]",1,outFileName);
  
  DrawNVtx("Run2012D",              "[Run2012D]",                 1,outFileName);
  DrawNVtx("Run2012D_HLTfire",      "[Run2012D - with HLT]",      1,outFileName);
  DrawNVtx("Run2012D_HLTfire_eleID","[Run2012D - with HLT+eleID]",1,outFileName);
  DrawNVtx("Run2012D_noPUWeight",   "[Run2012D - no PU reweigh.]",1,outFileName);
    
  outFile -> Close();
  dummy -> Print((outFileName+"."+extension+"]").c_str(),extension.c_str());
}
Esempio n. 9
0
int main(int argc, char** argv)
{
  //Check if all nedeed arguments to parse are there
  if(argc != 2)
  {
    std::cerr << ">>> compareZPeaks::usage: " << argv[0] << " configFileName" << std::endl;
    return -1;
  }
  
  
  
  //----------------------
  // Parse the config file
  
  parseConfigFile(argv[1]);
  
  std::string inputFilesDA = gConfigParser -> readStringOption("Input::inputFilesDA");
  std::string inputFilesMC = gConfigParser -> readStringOption("Input::inputFilesMC");
  
  std::string dataLabel  = gConfigParser -> readStringOption("Options::dataLabel");
  
  bool useShervinNtuple = gConfigParser -> readBoolOption("Options::useShervinNtuple");
  
  int maxEntries    = gConfigParser -> readIntOption("Options::maxEntries");
  std::string MCGen = gConfigParser -> readStringOption("Options::MCGen");
  bool runDepFlag   = gConfigParser -> readBoolOption("Options::runDepFlag");
  int runMin        = gConfigParser -> readIntOption("Options::runMin");
  int runMax        = gConfigParser -> readIntOption("Options::runMax");
  
  bool diagonalCatOnly = gConfigParser -> readBoolOption("Options::diagonalCatOnly");
  
  std::string eleIDSelection = gConfigParser -> readStringOption("Options::eleIDSelection");
  int eleIDBit = 1;
  if( eleIDSelection == "loose"  ) eleIDBit = 2;
  if( eleIDSelection == "medium" ) eleIDBit = 6;
  if( eleIDSelection == "tight"  ) eleIDBit = 14;
  if( eleIDSelection == "WP90PU" ) eleIDBit = 16;
  if( eleIDSelection == "WP80PU" ) eleIDBit = 48;
    
  bool applyPUWeight        = gConfigParser -> readBoolOption("Options::applyPUWeight");
  bool applyEnergyScaleCorr = gConfigParser -> readBoolOption("Options::applyEnergyScaleCorr");
  bool applyEnergySmearing  = gConfigParser -> readBoolOption("Options::applyEnergySmearing");
  
  std::string enCorrType          = gConfigParser -> readStringOption("Options::enCorrType");
  std::string energyScaleCorrType = gConfigParser -> readStringOption("Options::energyScaleCorrType");
  std::string energySmearingType  = gConfigParser -> readStringOption("Options::energySmearingType");
  
  std::string runRangeFile        = gConfigParser -> readStringOption("Options::runRangeFile");
  std::string ShervinScaleFile    = gConfigParser -> readStringOption("Options::ShervinScaleFile");
  std::string ShervinSmearingFile = gConfigParser -> readStringOption("Options::ShervinSmearingFile");
  std::string IJazZGlobalFolder   = gConfigParser -> readStringOption("Options::IJazZGlobalFolder");
  std::string IJazZRunDepFolder   = gConfigParser -> readStringOption("Options::IJazZRunDepFolder");
  
  bool doVoigtianFit    = gConfigParser -> readBoolOption("Options::doVoigtianFit");
  bool doCrystalBallFit = gConfigParser -> readBoolOption("Options::doCrystalBallFit");
  bool doEffectiveSigma = gConfigParser -> readBoolOption("Options::doEffectiveSigma");
  
  std::string outFilePath = gConfigParser -> readStringOption("Output::outFilePath");
  
  
  
  //------------------
  // Set style options
  
  setTDRStyle();
  gStyle->SetPadTopMargin(0.05);
  gStyle->SetPadBottomMargin(0.13);
  gStyle->SetPadLeftMargin(0.13);
  gStyle->SetPadRightMargin(0.17);
  gStyle->SetLabelSize(0.04,"XYZ");
  gStyle->SetTitleSize(0.05,"XYZ");
  gStyle->SetOptStat(0);
  gStyle->SetOptFit(0);
  
  
  
  //----------
  // Get trees
  std::cout << ">>> Get trees" << std::endl;  
  std::cout << std::endl;
  
  std::string treeName;
  if( !useShervinNtuple ) treeName = "simpleNtupleEoverP/SimpleNtupleEoverP";
  else                    treeName = "selected";
  
  TChain* ntu_MC = new TChain(treeName.c_str());
  FillChain(ntu_MC,inputFilesMC);
  std::cout << ">>>   MC: " << std::setw(8) << ntu_MC->GetEntries() << " entries" << std::endl;
  
  TChain* ntu_DA = new TChain(treeName.c_str());
  FillChain(ntu_DA,inputFilesDA);
  std::cout << ">>> DATA: " << std::setw(8) << ntu_DA->GetEntries() << " entries" << std::endl;
  
  if( ntu_MC->GetEntries() == 0 || ntu_DA->GetEntries() == 0 )
  {
    std::cout << ">>> compareZPeaks::Error: at least one file is empty" << std::endl; 
    return -1;
  }
  
  
  
  //------------------------
  // Define branch addresses
  std::cout << std::endl;
  std::cout << ">>> Define branch addresses" << std::endl;
  
  float scEta[2];
  float scE[2];
  float scERaw[2];
  float scEReg[2];
  float scETrue[2];
  float R9[2];
  int eleID[2];
  
  int runId;
  int isZ;
  bool HLTfire;
  int timeStampHigh;
  float mZ, mZTrue;
  int isEB1,isEB2;
  float scEta1,scEta2;
  float scERaw1,scERaw2;
  float scE1,scE2;
  float scEReg1,scEReg2;
  float scETrue1,scETrue2;
  float E3x31,E3x32;
  float R91,R92;
  int seedIeta1,seedIeta2;
  int seedIphi1,seedIphi2;
  int seedIx1,seedIx2;
  int seedIy1,seedIy2;
  int seedIz1,seedIz2;
  int eleID1, eleID2;
  int nPU;
  
  if( !useShervinNtuple )
  {
    HLTfire = true;
    
    ntu_DA -> SetBranchStatus("*",0);
    ntu_DA -> SetBranchStatus("runId",              1);   ntu_DA -> SetBranchAddress("runId",&runId);
    ntu_DA -> SetBranchStatus("isZ",                1);   ntu_DA -> SetBranchAddress("isZ",&isZ);
    ntu_DA -> SetBranchStatus("timeStampHigh",      1);   ntu_DA -> SetBranchAddress("timeStampHigh",&timeStampHigh);
    ntu_DA -> SetBranchStatus("ele1ele2_scM",       1);   ntu_DA -> SetBranchAddress("ele1ele2_scM",&mZ);
    ntu_DA -> SetBranchStatus("ele1_isEB",          1);   ntu_DA -> SetBranchAddress("ele1_isEB",&isEB1);
    ntu_DA -> SetBranchStatus("ele2_isEB",          1);   ntu_DA -> SetBranchAddress("ele2_isEB",&isEB2);
    ntu_DA -> SetBranchStatus("ele1_scEta",         1);   ntu_DA -> SetBranchAddress("ele1_scEta",&scEta1);
    ntu_DA -> SetBranchStatus("ele2_scEta",         1);   ntu_DA -> SetBranchAddress("ele2_scEta",&scEta2);
    ntu_DA -> SetBranchStatus("ele1_scERaw",        1);   ntu_DA -> SetBranchAddress("ele1_scERaw",&scERaw1);
    ntu_DA -> SetBranchStatus("ele2_scERaw",        1);   ntu_DA -> SetBranchAddress("ele2_scERaw",&scERaw2);
    ntu_DA -> SetBranchStatus("ele1_scE",           1);   ntu_DA -> SetBranchAddress("ele1_scE",&scE1);
    ntu_DA -> SetBranchStatus("ele2_scE",           1);   ntu_DA -> SetBranchAddress("ele2_scE",&scE2);
    if( enCorrType == "stdSC" )
    {
      ntu_DA -> SetBranchStatus("ele1_scE",1);   ntu_DA -> SetBranchAddress("ele1_scE",&scEReg1);
      ntu_DA -> SetBranchStatus("ele2_scE",1);   ntu_DA -> SetBranchAddress("ele2_scE",&scEReg2);
    }
    if( enCorrType == "eleTunedReg" )
    {
      ntu_DA -> SetBranchStatus("ele1_scE_regression",1);   ntu_DA -> SetBranchAddress("ele1_scE_regression",&scEReg1);
      ntu_DA -> SetBranchStatus("ele2_scE_regression",1);   ntu_DA -> SetBranchAddress("ele2_scE_regression",&scEReg2);
    }
    if( enCorrType == "phoTunedReg" )
    {
      ntu_DA -> SetBranchStatus("ele1_scE_regression_PhotonTuned",1);   ntu_DA -> SetBranchAddress("ele1_scE_regression_PhotonTuned",&scEReg1);
      ntu_DA -> SetBranchStatus("ele2_scE_regression_PhotonTuned",1);   ntu_DA -> SetBranchAddress("ele2_scE_regression_PhotonTuned",&scEReg2);
    }
    ntu_DA -> SetBranchStatus("ele1_e3x3",          1);   ntu_DA -> SetBranchAddress("ele1_e3x3",&E3x31);
    ntu_DA -> SetBranchStatus("ele2_e3x3",          1);   ntu_DA -> SetBranchAddress("ele2_e3x3",&E3x32);
    ntu_DA -> SetBranchStatus("ele1_seedIeta",      1);   ntu_DA -> SetBranchAddress("ele1_seedIeta",&seedIeta1);
    ntu_DA -> SetBranchStatus("ele2_seedIeta",      1);   ntu_DA -> SetBranchAddress("ele2_seedIeta",&seedIeta2);
    ntu_DA -> SetBranchStatus("ele1_seedIphi",      1);   ntu_DA -> SetBranchAddress("ele1_seedIphi",&seedIphi1);
    ntu_DA -> SetBranchStatus("ele2_seedIphi",      1);   ntu_DA -> SetBranchAddress("ele2_seedIphi",&seedIphi2);
    ntu_DA -> SetBranchStatus("ele1_seedIx",        1);   ntu_DA -> SetBranchAddress("ele1_seedIx",&seedIx1);
    ntu_DA -> SetBranchStatus("ele2_seedIx",        1);   ntu_DA -> SetBranchAddress("ele2_seedIx",&seedIx2);
    ntu_DA -> SetBranchStatus("ele1_seedIy",        1);   ntu_DA -> SetBranchAddress("ele1_seedIy",&seedIy1);
    ntu_DA -> SetBranchStatus("ele2_seedIy",        1);   ntu_DA -> SetBranchAddress("ele2_seedIy",&seedIy2);
    ntu_DA -> SetBranchStatus("ele1_seedZside",     1);   ntu_DA -> SetBranchAddress("ele1_seedZside",&seedIz1);
    ntu_DA -> SetBranchStatus("ele2_seedZside",     1);   ntu_DA -> SetBranchAddress("ele2_seedZside",&seedIz2);
    
    ntu_MC -> SetBranchStatus("*",0);
    ntu_MC -> SetBranchStatus("isZ",                1);   ntu_MC -> SetBranchAddress("isZ",&isZ);
    ntu_MC -> SetBranchStatus("timeStampHigh",      1);   ntu_MC -> SetBranchAddress("timeStampHigh",&timeStampHigh);
    ntu_MC -> SetBranchStatus("ele1ele2_scM",       1);   ntu_MC -> SetBranchAddress("ele1ele2_scM",&mZ);
    ntu_MC -> SetBranchStatus("ele1_isEB",          1);   ntu_MC -> SetBranchAddress("ele1_isEB",&isEB1);
    ntu_MC -> SetBranchStatus("ele2_isEB",          1);   ntu_MC -> SetBranchAddress("ele2_isEB",&isEB2);
    ntu_MC -> SetBranchStatus("ele1_scEta",         1);   ntu_MC -> SetBranchAddress("ele1_scEta",&scEta1);
    ntu_MC -> SetBranchStatus("ele2_scEta",         1);   ntu_MC -> SetBranchAddress("ele2_scEta",&scEta2);
    ntu_MC -> SetBranchStatus("ele1_scERaw",        1);   ntu_MC -> SetBranchAddress("ele1_scERaw",&scERaw1);
    ntu_MC -> SetBranchStatus("ele2_scERaw",        1);   ntu_MC -> SetBranchAddress("ele2_scERaw",&scERaw2);
    ntu_MC -> SetBranchStatus("ele1_scE",           1);   ntu_MC -> SetBranchAddress("ele1_scE",&scE1);
    ntu_MC -> SetBranchStatus("ele2_scE",           1);   ntu_MC -> SetBranchAddress("ele2_scE",&scE2);
    if( enCorrType == "stdSC" )
    {
      ntu_MC -> SetBranchStatus("ele1_scE",1);   ntu_MC -> SetBranchAddress("ele1_scE",&scEReg1);
      ntu_MC -> SetBranchStatus("ele2_scE",1);   ntu_MC -> SetBranchAddress("ele2_scE",&scEReg2);
    }
    if( enCorrType == "eleTunedReg" )
    {
      ntu_MC -> SetBranchStatus("ele1_scE_regression",1);   ntu_MC -> SetBranchAddress("ele1_scE_regression",&scEReg1);
      ntu_MC -> SetBranchStatus("ele2_scE_regression",1);   ntu_MC -> SetBranchAddress("ele2_scE_regression",&scEReg2);
    }
    if( enCorrType == "phoTunedReg" )
    {
      ntu_MC -> SetBranchStatus("ele1_scE_regression_PhotonTuned",1);   ntu_MC -> SetBranchAddress("ele1_scE_regression_PhotonTuned",&scEReg1);
      ntu_MC -> SetBranchStatus("ele2_scE_regression_PhotonTuned",1);   ntu_MC -> SetBranchAddress("ele2_scE_regression_PhotonTuned",&scEReg2);
    }
    ntu_MC -> SetBranchStatus("ele1_e3x3",          1);   ntu_MC -> SetBranchAddress("ele1_e3x3",&E3x31);
    ntu_MC -> SetBranchStatus("ele2_e3x3",          1);   ntu_MC -> SetBranchAddress("ele2_e3x3",&E3x32);
    ntu_MC -> SetBranchStatus("ele1_seedIeta",      1);   ntu_MC -> SetBranchAddress("ele1_seedIeta",&seedIeta1);
    ntu_MC -> SetBranchStatus("ele2_seedIeta",      1);   ntu_MC -> SetBranchAddress("ele2_seedIeta",&seedIeta2);
    ntu_MC -> SetBranchStatus("ele1_seedIphi",      1);   ntu_MC -> SetBranchAddress("ele1_seedIphi",&seedIphi1);
    ntu_MC -> SetBranchStatus("ele2_seedIphi",      1);   ntu_MC -> SetBranchAddress("ele2_seedIphi",&seedIphi2);
    ntu_MC -> SetBranchStatus("ele1_seedIx",        1);   ntu_MC -> SetBranchAddress("ele1_seedIx",&seedIx1);
    ntu_MC -> SetBranchStatus("ele2_seedIx",        1);   ntu_MC -> SetBranchAddress("ele2_seedIx",&seedIx2);
    ntu_MC -> SetBranchStatus("ele1_seedIy",        1);   ntu_MC -> SetBranchAddress("ele1_seedIy",&seedIy1);
    ntu_MC -> SetBranchStatus("ele2_seedIy",        1);   ntu_MC -> SetBranchAddress("ele2_seedIy",&seedIy2);
    ntu_MC -> SetBranchStatus("ele1_seedZside",     1);   ntu_MC -> SetBranchAddress("ele1_seedZside",&seedIz1);
    ntu_MC -> SetBranchStatus("ele2_seedZside",     1);   ntu_MC -> SetBranchAddress("ele2_seedZside",&seedIz2);
    ntu_MC -> SetBranchStatus("PUit_TrueNumInteractions",1); ntu_MC -> SetBranchAddress("PUit_TrueNumInteractions",&nPU);  
  }
  else
  {
    isZ = 1;
    
    ntu_MC -> SetBranchStatus("*",0);
    ntu_MC -> SetBranchStatus("HLTfire",       1);   ntu_MC -> SetBranchAddress("HLTfire",&HLTfire);
    ntu_MC -> SetBranchStatus("runNumber",     1);   ntu_MC -> SetBranchAddress("runNumber",&runId);
    ntu_MC -> SetBranchStatus("nPU",           1);   ntu_MC -> SetBranchAddress("nPU",&nPU);
    ntu_MC -> SetBranchStatus("R9Ele",         1);   ntu_MC -> SetBranchAddress("R9Ele",R9);
    ntu_MC -> SetBranchStatus("etaSCEle",      1);   ntu_MC -> SetBranchAddress("etaSCEle",scEta);
    ntu_MC -> SetBranchStatus("rawEnergySCEle",1);   ntu_MC -> SetBranchAddress("rawEnergySCEle",scERaw);
    ntu_MC -> SetBranchStatus("energyMCEle",   1);   ntu_MC -> SetBranchAddress("energyMCEle",scETrue);
    ntu_MC -> SetBranchStatus("energySCEle",   1);   ntu_MC -> SetBranchAddress("energySCEle",scE);
    if( enCorrType == "stdSC" )
    {
      ntu_MC -> SetBranchStatus("energySCEle",1);   ntu_MC -> SetBranchAddress("energySCEle",scEReg);
    }
    if( enCorrType == "eleTunedRegV3" )
    {
      ntu_MC -> SetBranchStatus("energySCEle_regrCorr_ele",1);   ntu_MC -> SetBranchAddress("energySCEle_regrCorr_ele",scEReg);
    }
    if( enCorrType == "phoTunedRegV3" )
    {
      ntu_MC -> SetBranchStatus("energySCEle_regrCorr_pho",1);   ntu_MC -> SetBranchAddress("energySCEle_regrCorr_pho",scEReg);
    }
    if( enCorrType == "eleTunedRegV4" )
    {
      ntu_MC -> SetBranchStatus("energySCEle_regrCorrSemiParV4_ele",1);   ntu_MC -> SetBranchAddress("energySCEle_regrCorrSemiParV4_ele",scEReg);
    }
    if( enCorrType == "phoTunedRegV4" )
    {
      ntu_MC -> SetBranchStatus("energySCEle_regrCorrSemiParV4_pho",1);   ntu_MC -> SetBranchAddress("energySCEle_regrCorrSemiParV4_pho",scEReg);
    }
    if( enCorrType == "eleTunedRegV5" )
    {
      ntu_MC -> SetBranchStatus("energySCEle_regrCorrSemiParV5_ele",1);   ntu_MC -> SetBranchAddress("energySCEle_regrCorrSemiParV5_ele",scEReg);
    }
    if( enCorrType == "phoTunedRegV5" )
    {
      ntu_MC -> SetBranchStatus("energySCEle_regrCorrSemiParV5_pho",1);   ntu_MC -> SetBranchAddress("energySCEle_regrCorrSemiParV5_pho",scEReg);
    }
    ntu_MC -> SetBranchStatus("invMass_SC",1);   ntu_MC -> SetBranchAddress("invMass_SC",&mZ);
    ntu_MC -> SetBranchStatus("eleID",     1);   ntu_MC -> SetBranchAddress("eleID",eleID);
    
    ntu_DA -> SetBranchStatus("*",0);
    ntu_DA -> SetBranchStatus("HLTfire",       1);   ntu_DA -> SetBranchAddress("HLTfire",&HLTfire);
    ntu_DA -> SetBranchStatus("runNumber",     1);   ntu_DA -> SetBranchAddress("runNumber",&runId);
    ntu_DA -> SetBranchStatus("R9Ele",         1);   ntu_DA -> SetBranchAddress("R9Ele",R9);
    ntu_DA -> SetBranchStatus("etaSCEle",      1);   ntu_DA -> SetBranchAddress("etaSCEle",scEta);
    ntu_DA -> SetBranchStatus("rawEnergySCEle",1);   ntu_DA -> SetBranchAddress("rawEnergySCEle",scERaw);
    ntu_DA -> SetBranchStatus("energySCEle",   1);   ntu_DA -> SetBranchAddress("energySCEle",scE);
    if( enCorrType == "stdSC" )
    {
      ntu_DA -> SetBranchStatus("energySCEle",1);   ntu_DA -> SetBranchAddress("energySCEle",scEReg);
    }
    if( enCorrType == "eleTunedRegV3" )
    {
      ntu_DA -> SetBranchStatus("energySCEle_regrCorr_ele",1);   ntu_DA -> SetBranchAddress("energySCEle_regrCorr_ele",scEReg);
    }
    if( enCorrType == "phoTunedRegV3" )
    {
      ntu_DA -> SetBranchStatus("energySCEle_regrCorr_pho",1);   ntu_DA -> SetBranchAddress("energySCEle_regrCorr_pho",scEReg);
    }
    if( enCorrType == "eleTunedRegV4" )
    {
      ntu_DA -> SetBranchStatus("energySCEle_regrCorrSemiParV4_ele",1);   ntu_DA -> SetBranchAddress("energySCEle_regrCorrSemiParV4_ele",scEReg);
    }
    if( enCorrType == "phoTunedRegV4" )
    {
      ntu_DA -> SetBranchStatus("energySCEle_regrCorrSemiParV4_pho",1);   ntu_DA -> SetBranchAddress("energySCEle_regrCorrSemiParV4_pho",scEReg);
    }
    if( enCorrType == "eleTunedRegV5" )
    {
      ntu_DA -> SetBranchStatus("energySCEle_regrCorrSemiParV5_ele",1);   ntu_DA -> SetBranchAddress("energySCEle_regrCorrSemiParV5_ele",scEReg);
    }
    if( enCorrType == "phoTunedRegV5" )
    {
      ntu_DA -> SetBranchStatus("energySCEle_regrCorrSemiParV5_pho",1);   ntu_DA -> SetBranchAddress("energySCEle_regrCorrSemiParV5_pho",scEReg);
    }
    ntu_DA -> SetBranchStatus("invMass_SC",1);   ntu_DA -> SetBranchAddress("invMass_SC", &mZ);
    ntu_DA -> SetBranchStatus("eleID",     1);   ntu_DA -> SetBranchAddress("eleID",eleID);
  }
  
  
  
  //------------------
  // Define categories
  std::cout << std::endl;
  std::cout << ">>> Define categories" << std::endl;
    
  std::vector<std::string> categories;
  std::vector<std::string> categoryLabels;
  
  categories.push_back("EB-EB");
  categoryLabels.push_back("EB-EB");
  categories.push_back("EB-EB_hR9");
  categoryLabels.push_back("EB-EB   R9>0.94");
  categories.push_back("EB-EB_lR9");
  categoryLabels.push_back("EB-EB   R9<0.94");
  categories.push_back("EB-EB_eta>1");
  categoryLabels.push_back("EB-EB   |#eta|>1");
  categories.push_back("EB-EB_eta<1");
  categoryLabels.push_back("EB-EB   |#eta|<1");
  
  categories.push_back("EE-EE");
  categoryLabels.push_back("EE-EE");
  categories.push_back("EE-EE_hR9");
  categoryLabels.push_back("EE-EE   R9>0.94");
  categories.push_back("EE-EE_lR9");
  categoryLabels.push_back("EE-EE   R9<0.94");
  categories.push_back("EE-EE_eta>2");
  categoryLabels.push_back("EE-EE   |#eta|>2");
  categories.push_back("EE-EE_eta<2");
  categoryLabels.push_back("EE-EE   |#eta|<2");
  
  std::vector<float> etaBins;
  etaBins.push_back(0.0);
  etaBins.push_back(1.0);
  etaBins.push_back(1.5);
  etaBins.push_back(2.0);
  etaBins.push_back(2.5);
  int nEtaBins = int(etaBins.size()) - 1;
  
  std::vector<float> R9Bins;
  R9Bins.push_back(0.00);
  R9Bins.push_back(0.94);
  R9Bins.push_back(1.00);
  int nR9Bins = int(R9Bins.size()) - 1;
  
  std::vector<std::string> singleCats;
  std::vector<std::string> singleCatLabels;
  for(int etaBin = 0; etaBin < nEtaBins; ++etaBin)
    for(int R9Bin = 0; R9Bin < nR9Bins; ++R9Bin)
    {
      singleCats.push_back(Form("eta%1.1f-%1.1f_R9%1.2f-%1.2f",etaBins.at(etaBin),etaBins.at(etaBin+1),R9Bins.at(R9Bin),R9Bins.at(R9Bin+1)));
      singleCatLabels.push_back(Form("%1.1f<|#eta|<%1.1f %1.2f<R9<%1.2f",etaBins.at(etaBin),etaBins.at(etaBin+1),R9Bins.at(R9Bin),R9Bins.at(R9Bin+1)));
    }
  
  for(unsigned int i = 0; i < singleCats.size(); ++i)
    for(unsigned int j = i; j < singleCats.size(); ++j)
    {
      if( diagonalCatOnly && (j != i ) ) continue;
      
      categories.push_back(singleCats.at(i) + "__" + singleCats.at(j));
      categoryLabels.push_back(Form("%s %s",singleCatLabels.at(i).c_str(),singleCatLabels.at(j).c_str()));
      std::cout << ">>>>>> " << singleCats.at(i) + "__" + singleCats.at(j) << std::endl;
    }
  
  
  
  //------------------
  // Define histograms
  std::cout << std::endl;
  std::cout << ">>> Define histograms" << std::endl;
    
  for(unsigned int i = 0; i < categories.size(); ++i)
  {
    std::string category = categories.at(i);
    
    std::string histoName = "h_mZ_MC_"+category;
    h_mZ_MC[category] = new TH1F(histoName.c_str(),"",100,meeMin,meeMax);
    h_mZ_MC[category] -> Sumw2();
    
    histoName = "h_mZFine_MC_"+category;
    h_mZFine_MC[category] = new TH1F(histoName.c_str(),"",int((meeFineMax-meeFineMin)/precision),meeFineMin,meeFineMax);
    h_mZFine_MC[category] -> Sumw2();
    
    histoName = "h_mZRes_MC_"+category;
    h_mZRes_MC[category] = new TH1F(histoName.c_str(),"",10000,0.,2.);
    h_mZRes_MC[category] -> Sumw2();
    
    histoName = "h_mZ_DA_"+category;
    h_mZ_DA[category] = new TH1F(histoName.c_str(),"",100,meeMin,meeMax);
    h_mZ_DA[category] -> Sumw2();
    
    histoName = "h_mZFine_DA_"+category;
    h_mZFine_DA[category] = new TH1F(histoName.c_str(),"",int((meeFineMax-meeFineMin)/precision),meeFineMin,meeFineMax);
    h_mZFine_DA[category] -> Sumw2();
  }
  
  
  
  //-----------------------------
  // Setup data scale corrections
  std::cout << std::endl;
  std::cout << ">>> Setup data scale corrections" << std::endl;
  
  ScaleCorrector* myScaleCorrector = new ScaleCorrector(runRangeFile);
  
  if( applyEnergyScaleCorr )
  {
    if( energyScaleCorrType == "shervin" ) myScaleCorrector -> SetShervinRunDepScaleMap(ShervinScaleFile);
    if( energyScaleCorrType == "fabrice" ) myScaleCorrector -> SetIJazZGlobalScaleHisto(IJazZGlobalFolder);
    if( energyScaleCorrType == "fabrice" ) myScaleCorrector -> SetIJazZRunDepScaleHistoMap(IJazZRunDepFolder);
  }
  
  
  
  //-----------------------
  // Setup MC extrasmearing
  std::cout << std::endl;
  std::cout << ">>> Setup MC extrasmearing" << std::endl;
  
  Smearer* mySmearer = new Smearer();
  
  if( applyEnergySmearing )
  {
    if( energyScaleCorrType == "shervin" ) mySmearer -> SetShervinExtraSmearingMap(ShervinSmearingFile);
    if( energyScaleCorrType == "fabrice" ) mySmearer -> SetIJazZExtraSmearingHisto(IJazZGlobalFolder);
  }
  
  
  
  //--------------------------
  // pileup reweighting for MC
  std::cout << std::endl;
  std::cout << ">>> Setup MC pileup reweighting" << std::endl;
  
  std::map<std::string, TH1F*>* PUWeights = ReadPUWeights(MCGen,runDepFlag,runMin,runMax);
  
  
  
  
  
  
  //------------------
  // Loop over entries
  std::cout << std::endl;
  std::cout << ">>> Read data from MC sample" << std::endl;
  
  int nEntries_MC = ntu_MC -> GetEntriesFast();
  for(int ientry = 0; ientry < nEntries_MC; ++ientry)
  {
    if( maxEntries != -1 && ientry == maxEntries ) break;
    if( ientry%100000 == 0 ) std::cout << ">>>>>> reading   MC entry " << ientry << " / " << nEntries_MC << "\r"<< std::flush;
    ntu_MC -> GetEntry(ientry);
    
    // variables
    R91 = E3x31/scERaw1;
    R92 = E3x32/scERaw2;
    
    if( useShervinNtuple )
    {
      R91 = R9[0];
      R92 = R9[1];
      scEta1 = scEta[0];
      scEta2 = scEta[1];
      scEReg1 = scEReg[0];
      scEReg2 = scEReg[1];
      scE1 = scE[0];
      scE2 = scE[1];
      eleID1 = eleID[0];
      eleID2 = eleID[1];
      scETrue1 = scETrue[0];
      scETrue2 = scETrue[1];
    }
    else
    {
      eleID1 = 7;
      eleID2 = 7;
    }
    
    
    // selections
    if( isZ != 1 ) continue;
    if( !HLTfire ) continue;
    if( fabs(scEta1) >= 2.5000 || fabs(scEta2) >= 2.5000  ) continue;
    if( fabs(scEta1) >  1.4442 && fabs(scEta1) <  1.5660 ) continue;
    if( fabs(scEta2) >  1.4442 && fabs(scEta2) <  1.5660 ) continue;
    if( R91 < 0.0 || R91 >= 1.0 ) continue;
    if( R92 < 0.0 || R92 >= 1.0 ) continue;
    if( ((eleID1 & eleIDBit) != eleIDBit) || ((eleID2 & eleIDBit) != eleIDBit) ) continue;
    
    
    if( applyEnergySmearing )
    {
      float energySmearing1 = gRandom->Gaus(1.,mySmearer->GetExtraSmearing(scEta1,R91,dataLabel,energySmearingType));
      float energySmearing2 = gRandom->Gaus(1.,mySmearer->GetExtraSmearing(scEta2,R92,dataLabel,energySmearingType));
      scEReg1 *= energySmearing1;
      scEReg2 *= energySmearing2;
    }
    
    float ww = 1.;
    if( applyPUWeight )
    {
      std::string periodLabel = getPeriodLabel(runId,runDepFlag,runMin,runMax);
      
      int ibin = (*PUWeights)[periodLabel] -> FindBin( nPU );
      if( ibin <= 1 ) ibin = 1;
      if( ibin >= (*PUWeights)[periodLabel]->GetNbinsX() ) ibin = (*PUWeights)[periodLabel]->GetNbinsX();
      ww *= (*PUWeights)[periodLabel]->GetBinContent(ibin);
    }
    
    
    // use regression energy
    mZTrue = mZ * sqrt( scETrue1/scE1 * scETrue2/scE2 ); 
    mZ *= sqrt( scEReg1/scE1 * scEReg2/scE2 );
            
    // fill EB histograms
    if( (fabs(scEta1) < 1.5) && (fabs(scEta2) < 1.5) )
    {
      h_mZ_MC["EB-EB"] -> Fill( mZ,ww );
      h_mZFine_MC["EB-EB"] -> Fill( mZ,ww );
      h_mZRes_MC["EB-EB"] -> Fill( mZ/mZTrue,ww );
      
      if( (R91 > 0.94) && (R92 > 0.94) )
      {
        h_mZ_MC["EB-EB_hR9"] -> Fill( mZ,ww );
        h_mZFine_MC["EB-EB_hR9"] -> Fill( mZ,ww );
        h_mZRes_MC["EB-EB_hR9"] -> Fill( mZ/mZTrue,ww );
      }
      
      if( (R91 < 0.94) && (R92 < 0.94) )
      {
        h_mZ_MC["EB-EB_lR9"] -> Fill( mZ,ww );
        h_mZFine_MC["EB-EB_lR9"] -> Fill( mZ,ww );
        h_mZRes_MC["EB-EB_lR9"] -> Fill( mZ/mZTrue,ww );
      }
      
      if( (fabs(scEta1) > 1.) && (fabs(scEta2) > 1.) )
      {
        h_mZ_MC["EB-EB_eta>1"] -> Fill( mZ,ww );
        h_mZFine_MC["EB-EB_eta>1"] -> Fill( mZ,ww );
        h_mZRes_MC["EB-EB_eta>1"] -> Fill( mZ/mZTrue,ww );
      }
      
      if( (fabs(scEta1) < 1.) && (fabs(scEta2) < 1.) )
      {
        h_mZ_MC["EB-EB_eta<1"] -> Fill( mZ,ww );
        h_mZFine_MC["EB-EB_eta<1"] -> Fill( mZ,ww );
        h_mZRes_MC["EB-EB_eta<1"] -> Fill( mZ/mZTrue,ww );
      }
    }
    
    
    // fill EE histograms
    if( (fabs(scEta1) > 1.5) && (fabs(scEta2) > 1.5) )
    {
      h_mZ_MC["EE-EE"] -> Fill( mZ,ww );
      h_mZFine_MC["EE-EE"] -> Fill( mZ,ww );
      h_mZRes_MC["EE-EE"] -> Fill( mZ/mZTrue,ww );
      
      if( (R91 > 0.94) && (R92 > 0.94) )
      {
        h_mZ_MC["EE-EE_hR9"] -> Fill( mZ,ww );
        h_mZFine_MC["EE-EE_hR9"] -> Fill( mZ,ww );
        h_mZRes_MC["EE-EE_hR9"] -> Fill( mZ/mZTrue,ww );
      }
      
      if( (R91 < 0.94) && (R92 < 0.94) )
      {
        h_mZ_MC["EE-EE_lR9"] -> Fill( mZ,ww );
        h_mZFine_MC["EE-EE_lR9"] -> Fill( mZ,ww );
        h_mZRes_MC["EE-EE_lR9"] -> Fill( mZ/mZTrue,ww );
      }
      
      if( (fabs(scEta1) > 2.) && (fabs(scEta2) > 2.) )
      {
        h_mZ_MC["EE-EE_eta>2"] -> Fill( mZ,ww );
        h_mZFine_MC["EE-EE_eta>2"] -> Fill( mZ,ww );
        h_mZRes_MC["EE-EE_eta>2"] -> Fill( mZ/mZTrue,ww );
      }
      
      if( (fabs(scEta1) < 2.) && (fabs(scEta2) < 2.) )
      {
        h_mZ_MC["EE-EE_eta<2"] -> Fill( mZ,ww );
        h_mZFine_MC["EE-EE_eta<2"] -> Fill( mZ,ww );
        h_mZRes_MC["EE-EE_eta<2"] -> Fill( mZ/mZTrue,ww );
      }
    }
    
    
    // fill all independent categories
    std::string catLabel = GetEtaR9CatLabel(fabs(scEta1),R91,fabs(scEta2),R92,etaBins,R9Bins,categories);
    if( catLabel != "undefined__undefined" )
    {
      h_mZ_MC[catLabel] -> Fill( mZ,ww );
      h_mZFine_MC[catLabel] -> Fill( mZ,ww );
      h_mZRes_MC[catLabel] -> Fill( mZ/mZTrue,ww );
    }
  }
  std::cout << std::endl;
  
  
  
  std::cout << ">>> Read data from DATA sample" << std::endl;
  
  int nEntries_DA = ntu_DA -> GetEntriesFast();
  for(int ientry = 0; ientry < nEntries_DA; ++ientry)
  {
    if( maxEntries != -1 && ientry == maxEntries ) break;
    if( ientry%100000 == 0 ) std::cout << ">>>>>> reading DATA entry " << ientry << " / " << nEntries_DA << "\r" << std::flush;
    ntu_DA -> GetEntry(ientry);
    
    
    // variables
    R91 = E3x31/scERaw1;
    R92 = E3x32/scERaw2;
    
    if( useShervinNtuple )
    {
      R91 = R9[0];
      R92 = R9[1];
      scEta1 = scEta[0];
      scEta2 = scEta[1];
      scEReg1 = scEReg[0];
      scEReg2 = scEReg[1];
      scE1 = scE[0];
      scE2 = scE[1];
      eleID1 = eleID[0];
      eleID2 = eleID[1];
    }
    else
    {
      eleID1 = 7;
      eleID2 = 7;
    }
    
    
    // selections
    if( isZ != 1 ) continue;
    if( !HLTfire ) continue;
    if( fabs(scEta1) >= 2.5000 || fabs(scEta2) >= 2.5000  ) continue;
    if( fabs(scEta1) >  1.4442 && fabs(scEta1) <  1.5660 ) continue;
    if( fabs(scEta2) >  1.4442 && fabs(scEta2) <  1.5660 ) continue;
    if( R91 < 0.0 || R91 >= 1.0 ) continue;
    if( R92 < 0.0 || R92 >= 1.0 ) continue;
    if( ((eleID1 & eleIDBit) != eleIDBit) || ((eleID2 & eleIDBit) != eleIDBit) ) continue;    
    
    
    if( applyEnergyScaleCorr )
    {
      scEReg1 *= myScaleCorrector->GetScaleCorrection(scEta1,R91,runId,dataLabel,energyScaleCorrType);
      scEReg2 *= myScaleCorrector->GetScaleCorrection(scEta2,R92,runId,dataLabel,energyScaleCorrType);
    }
    
    
    // use regression energy
    mZ *= sqrt( scEReg1/scE1 * scEReg2/scE2 );
    
    
    // fill EB histograms
    if( (fabs(scEta1) < 1.5) && (fabs(scEta2) < 1.5) )
    {
      h_mZ_DA["EB-EB"]  ->  Fill( mZ );
      h_mZFine_DA["EB-EB"]  ->  Fill( mZ );
      
      if( (R91 > 0.94) && (R92 > 0.94) )
      {
        h_mZ_DA["EB-EB_hR9"]  ->  Fill( mZ );
        h_mZFine_DA["EB-EB_hR9"]  ->  Fill( mZ );
      }
      
      if( (R91 < 0.94) && (R92 < 0.94) )
      {
        h_mZ_DA["EB-EB_lR9"]  ->  Fill( mZ );
        h_mZFine_DA["EB-EB_lR9"]  ->  Fill( mZ );
      }
      
      if( (fabs(scEta1) > 1.) && (fabs(scEta2) > 1.) )
      {
        h_mZ_DA["EB-EB_eta>1"]  ->  Fill( mZ );
        h_mZFine_DA["EB-EB_eta>1"]  ->  Fill( mZ );
      }
      
      if( (fabs(scEta1) < 1.) && (fabs(scEta2) < 1.) )
      {
        h_mZ_DA["EB-EB_eta<1"]  ->  Fill( mZ );
        h_mZFine_DA["EB-EB_eta<1"]  ->  Fill( mZ );
      }
    }
    
    
    // fill EE histograms
    if( (fabs(scEta1) > 1.5) && (fabs(scEta2) > 1.5) )
    {
      h_mZ_DA["EE-EE"]  ->  Fill( mZ );
      h_mZFine_DA["EE-EE"]  ->  Fill( mZ );
      
      if( (R91 > 0.94) && (R92 > 0.94) )
      {
        h_mZ_DA["EE-EE_hR9"]  ->  Fill( mZ );
        h_mZFine_DA["EE-EE_hR9"]  ->  Fill( mZ );
      }
      
      if( (R91 < 0.94) && (R92 < 0.94) )
      {
        h_mZ_DA["EE-EE_lR9"]  ->  Fill( mZ );
        h_mZFine_DA["EE-EE_lR9"]  ->  Fill( mZ );
      }
      
      if( (fabs(scEta1) > 2.) && (fabs(scEta2) > 2.) )
      {
        h_mZ_DA["EE-EE_eta>2"]  ->  Fill( mZ );
        h_mZFine_DA["EE-EE_eta>2"]  ->  Fill( mZ );
      }
      
      if( (fabs(scEta1) < 2.) && (fabs(scEta2) < 2.) )
      {
        h_mZ_DA["EE-EE_eta<2"]  ->  Fill( mZ );
        h_mZFine_DA["EE-EE_eta<2"]  ->  Fill( mZ );
      }
    }
    
    
    // fill all independent categories
    std::string catLabel = GetEtaR9CatLabel(fabs(scEta1),R91,fabs(scEta2),R92,etaBins,R9Bins,categories);
    if( catLabel != "undefined__undefined" )
    {
      h_mZ_DA[catLabel] -> Fill( mZ );
      h_mZFine_DA[catLabel] -> Fill( mZ );
    }
  }
  std::cout << std::endl;
  
  
  
  //---------
  // Drawings
  std::cout << ">>> Drawings" << std::endl;
  
  std::string folderName = outFilePath + "/" + dataLabel + "/";
  gSystem -> mkdir(folderName.c_str());
  if( energySmearingType == "fabrice" ) folderName += IJazZGlobalFolder + "/";
  gSystem -> mkdir(folderName.c_str());
  
  std::string outFileName = folderName + "/compareZPeaks";
  
  outFileName += "__" + enCorrType;
  outFileName += "__MC_" + MCGen;
  if( applyPUWeight )        outFileName += "__MC_PUweight";
  if( applyEnergySmearing )  outFileName += "__MC_energySmearing_" + energySmearingType;
  if( applyEnergyScaleCorr ) outFileName += "__DA_energyScaleCorr_" + energyScaleCorrType;
  
  outFile = new TFile((outFileName+".root").c_str(),"RECREATE");
  
  
  TCanvas* dummy = new TCanvas("dummy","",0,0,800,600);
  dummy -> Print((outFileName+"."+extension+"[").c_str(),extension.c_str());
  
  for(unsigned int cat = 0; cat < categories.size(); ++cat)
  {
    std::string category = categories.at(cat);
    DrawZPeak(categories.at(cat),categoryLabels.at(cat),1,doVoigtianFit,doCrystalBallFit,doEffectiveSigma,"EBEE",outFileName);
  }
  
  outFile -> Close();
  dummy -> Print((outFileName+"."+extension+"]").c_str(),extension.c_str());}
Esempio n. 10
0
void trisCheckRegion(Char_t* EBEE = 0)
{
  // Set style options
  gROOT->Reset();
  gROOT->SetStyle("Plain");
  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);
  gStyle->SetOptTitle(0); 
  gStyle->SetOptStat(1110); 
  gStyle->SetOptFit(1); 
  
  

  // Check qualifiers
  if ( strcmp(EBEE,"EB")!=0 && strcmp(EBEE,"EE")!=0 )
  {
    std::cout << "CHK-STB Error: unknown partition " << EBEE << std::endl;
    std::cout << "CHK-STB Select either EB or EE ! " << std::endl;
    return;
  }
  
  
  
  // Define region
  EBregionBuilder* region = BuildEBRegion("inputREGION.txt");
  TH2F* h_EBRegion = region->DrawEBRegion();
  
  TCanvas* c_EBRegion = new TCanvas("c_EBRegion","EBRegion");
  c_EBRegion -> cd();
  h_EBRegion -> Draw("COLZ");
  
  
  // Get trees
  std::cout << std::endl;
  
  TChain* ntu_DA = new TChain("ntu");
  FillChain(ntu_DA,"inputDATA.txt");
  std::cout << "     DATA: " << std::setw(8) << ntu_DA->GetEntries() << " entries" << std::endl;
  
  TChain* ntu_MC = new TChain("ntu");
  FillChain(ntu_MC,"inputMC.txt");
  std::cout << "REFERENCE: " << std::setw(8) << ntu_MC->GetEntries() << " entries" << std::endl;
  
  if (ntu_DA->GetEntries() == 0 || ntu_MC->GetEntries() == 0 )
  {
    std::cout << "CHK-STB Error: At least one file is empty" << std::endl; 
    return;
  }
  
  
  
/////  // Set branch addresses
/////  int isW, isZ;
/////  float EoP, scEta;
/////  int seedIeta, seedIphi, seedIx, seedIy, seedZside;
/////  
/////  ntu_DA->SetBranchAddress("isW", &isW);
/////  ntu_DA->SetBranchAddress("isZ", &isZ);
/////  ntu_DA->SetBranchAddress("ele1_scEta", &scEta);
/////  ntu_DA->SetBranchAddress("ele1_EOverP", &EoP);
/////  ntu_DA->SetBranchAddress("ele1_seedIeta", &seedIeta);
/////  ntu_DA->SetBranchAddress("ele1_seedIphi", &seedIphi);
/////  ntu_DA->SetBranchAddress("ele1_seedIx", &seedIx);
/////  ntu_DA->SetBranchAddress("ele1_seedIy", &seedIy);
/////  ntu_DA->SetBranchAddress("ele1_seedZside", &seedZside);
/////  
/////  ntu_MC->SetBranchAddress("isW", &isW);
/////  ntu_MC->SetBranchAddress("isZ", &isZ);
/////  ntu_MC->SetBranchAddress("ele1_scEta", &scEta);
/////  ntu_MC->SetBranchAddress("ele1_EOverP", &EoP);
/////  
/////  
/////  
/////  // Build the reference from 'infile2'
/////  std::cout << std::endl;
/////  std::cout << "***** Build reference *****" << std::endl;
/////  
/////  TH1F* h_template = new TH1F("template", "", 1200, 0., 3.);
/////
/////  for(int ientry = 0; ientry < ntu_MC->GetEntries(); ++ientry)
/////  {
/////    if( (ientry%100000 == 0) ) std::cout << "reading MC entry " << ientry << std::endl;
/////    ntu_MC->GetEntry(ientry);
/////    if (strcmp(EBEE,"EB")==0 && fabs(scEta) > 1.45) continue;                       // barrel
/////    if (strcmp(EBEE,"EE")==0 && (fabs(scEta) < 1.47 || fabs(scEta)>2.7 )) continue; // endcap
/////    
/////    //if( fabs(scEta) > 0.44 ) continue;
/////    //if( fabs(scEta) < 0.44 || fabs(scEta) > 0.77 ) continue;
/////    //if( fabs(scEta) < 0.77 || fabs(scEta) > 1.10 ) continue;
/////    //if( fabs(scEta) < 1.10 || fabs(scEta) > 1.56 ) continue;
/////    //if( fabs(scEta) < 1.56 || fabs(scEta) > 2.00 ) continue;
/////    
/////    //if( fabs(scEta) > 0.77 ) continue;
/////    //if( fabs(scEta) < 0.77 || fabs(scEta) > 1.4442 ) continue;
/////    
/////    h_template -> Fill(EoP);
/////  }
/////  
/////  std::cout << "Reference built for " << EBEE << " - " << h_template->GetEntries() << " events" << std::endl;
/////  TCanvas* c_reference = new TCanvas("c_reference","reference");
/////  c_reference -> cd();
/////  h_template -> Draw();
/////  
/////  
/////  
/////  // Loop and sort events
/////  std::cout << std::endl;
/////  std::cout << "***** Sort events and define bins *****" << std::endl;
/////  
/////  int nEntries = ntu_DA -> GetEntriesFast(); 
/////  int nSavePts = 0; 
/////  std::vector<bool> isSavedEntries(nEntries);
/////  std::vector<Sorter> sortedEntries;
/////  std::vector<int> timeStampFirst;
/////    
/////  for(int ientry = 0; ientry < nEntries; ++ientry)  {
/////    ntu_DA -> GetEntry(ientry);
/////    isSavedEntries.at(ientry) = false;
/////    
/////    // save only what is needed for the analysis!!!
/////    if (strcmp(EBEE,"EB")==0 && fabs(scEta) > 1.45) continue;                       // barrel
/////    if (strcmp(EBEE,"EE")==0 && (fabs(scEta) < 1.47 || fabs(scEta)>2.7 )) continue; // endcap
/////    if( timeStampHigh < t1 ) continue;
/////    if( timeStampHigh > t2 ) continue;
/////    
/////    //if( fabs(scEta) > 0.44 ) continue;
/////    //if( fabs(scEta) < 0.44 || fabs(scEta) > 0.77 ) continue;
/////    //if( fabs(scEta) < 0.77 || fabs(scEta) > 1.10 ) continue;
/////    //if( fabs(scEta) < 1.10 || fabs(scEta) > 1.56 ) continue;
/////    //if( fabs(scEta) < 1.56 || fabs(scEta) > 2.00 ) continue;
/////    
/////    //if( fabs(scEta) > 0.77 ) continue;
/////    //if( fabs(scEta) < 0.77 || fabs(scEta) > 1.4442 ) continue;
/////    
/////    //if( (seedIeta > 0 && (seedIphi >= 100 && seedIphi < 121) ) ||
/////    //    (seedIeta < 0 && (seedIphi >= 160 && seedIphi < 180) ) ||
/////    //    (seedIeta < 0 && (seedIphi >= 300 && seedIphi < 320) ) )
/////    
/////    isSavedEntries.at(ientry) = true;
/////        
/////    Sorter dummy;
/////    dummy.time = timeStampHigh;
/////    dummy.entry = ientry;
/////    sortedEntries.push_back(dummy);
/////    
/////    nSavePts++;
/////  }
/////  std::sort(sortedEntries.begin(),sortedEntries.end(),Sorter());
/////  std::cout << "Data sorted in " << EBEE << " - " << nSavePts << " events" << std::endl;
/////  
/////  
/////  // Loop and define bins
/////  
/////  // "wide" bins - find events with time separation bigger than 1 day
/////  int nWideBins = 1;
/////  std::vector<int> wideBinEntryMax;
/////  int timeStampOld = -1;
/////  
/////  wideBinEntryMax.push_back(0);  
/////  for(int iSaved = 0; iSaved < nSavePts; ++iSaved)
/////  {
/////    if( iSaved%100000 == 0 ) std::cout << "reading saved entry " << iSaved << std::endl;
/////    ntu_DA->GetEntry(sortedEntries[iSaved].entry);  
/////    
/////    if( iSaved == 0 )
/////    {
/////      timeStampOld = timeStampHigh;
/////      continue;
/////    }
/////    
/////    if( (timeStampHigh-timeStampOld)/3600. > timeLapse )
/////    {
/////      ++nWideBins;
/////      wideBinEntryMax.push_back(iSaved-1);
/////    }
/////    
/////    timeStampOld = timeStampHigh;
/////  }
/////  wideBinEntryMax.push_back(nSavePts);
/////  
/////  // bins with approximatively evtsPerPoint events per bin
/////  int nBins = 0;
/////  std::vector<int> binEntryMax;
/////  
/////  binEntryMax.push_back(0);
/////  for(int wideBin = 0; wideBin < nWideBins; ++wideBin)
/////  {
/////    int nTempBins = std::max(1,int( (wideBinEntryMax.at(wideBin+1)-wideBinEntryMax.at(wideBin))/evtsPerPoint ));
/////    int nTempBinEntries = int( (wideBinEntryMax.at(wideBin+1)-wideBinEntryMax.at(wideBin))/nTempBins );
/////    
/////    for(int tempBin = 0; tempBin < nTempBins; ++tempBin)
/////    {
/////      ++nBins;
/////      if( tempBin < nTempBins - 1 )
/////        binEntryMax.push_back( wideBinEntryMax.at(wideBin) + (tempBin+1)*nTempBinEntries );
/////      else
/////        binEntryMax.push_back( wideBinEntryMax.at(wideBin+1) );
/////    }
/////  }
/////  
/////  std::cout << "nBins = " << nBins << std::endl;
/////  //for(int bin = 0; bin < nBins; ++bin)
/////  //  std::cout << "bin: " << bin
/////  //            << "   entry min: " << setw(6) << binEntryMax.at(bin)
/////  //            << "   entry max: " << setw(6) << binEntryMax.at(bin+1)
/////  //            << "   events: "    << setw(6) << binEntryMax.at(bin+1)-binEntryMax.at(bin)
/////  //            << std::endl;
/////  TVirtualFitter::SetDefaultFitter("Fumili2");
/////  
/////  
/////  
/////  // histogram definition
/////  TH2F* h_seedOccupancy_EB  = new TH2F("h_seedOccupancy_EB","",  171, -85., 86., 361,   0.,361.);
/////  TH2F* h_seedOccupancy_EEp = new TH2F("h_seedOccupancy_EEp","", 101,   0.,101., 100,   0.,101.);
/////  TH2F* h_seedOccupancy_EEm = new TH2F("h_seedOccupancy_EEm","", 101,   0.,101., 100,   0.,101.);
/////  
/////  TH1F* h_EoP_spread;
/////  TH1F* h_EoC_spread;
/////  
/////  if ( strcmp(EBEE,"EB")==0 )
/////  {  
/////    h_EoP_spread = new TH1F("h_EoP_spread","",100,0.965,1.010);
/////    h_EoC_spread = new TH1F("h_EoC_spread","",100,0.965,1.010);    
/////  }
/////  else 
/////  {  
/////    h_EoP_spread = new TH1F("h_EoP_spread","",100,0.880,1.030);
/////    h_EoC_spread = new TH1F("h_EoC_spread","",100,0.880,1.030);
/////  }
/////  
/////  h_EoP_spread -> SetLineColor(kRed+2);
/////  h_EoP_spread -> SetLineWidth(2);
/////  h_EoP_spread -> GetXaxis() -> SetTitle("Relative E/p scale");
/////
/////  h_EoC_spread -> SetLineColor(kGreen+2);
/////  h_EoC_spread -> SetLineWidth(2);
/////  h_EoC_spread -> GetXaxis() -> SetTitle("Relative E/p scale");
/////  
/////  
/////  TH1F** h_EoP = new TH1F*[nBins];
/////  TH1F** h_EoC = new TH1F*[nBins];
/////  TH1F** h_Las = new TH1F*[nBins];
/////  
/////  for(int i = 0; i < nBins; ++i)
/////  {
/////    char histoName[80];
/////    
/////    sprintf(histoName, "EoP_%d", i);
/////    h_EoP[i] = new TH1F(histoName, histoName, 1200, 0., 3.);
/////    h_EoP[i] -> SetFillColor(kRed+2);
/////    h_EoP[i] -> SetFillStyle(3004);
/////    h_EoP[i] -> SetMarkerStyle(7);
/////    h_EoP[i] -> SetMarkerColor(kRed+2);
/////    h_EoP[i] -> SetLineColor(kRed+2);
/////    
/////    sprintf(histoName, "EoC_%d", i);
/////    h_EoC[i] = new TH1F(histoName, histoName, 1200, 0., 3.);
/////    h_EoC[i] -> SetFillColor(kGreen+2);
/////    h_EoC[i] -> SetFillStyle(3004);
/////    h_EoC[i] -> SetMarkerStyle(7);
/////    h_EoC[i] -> SetMarkerColor(kGreen+2);
/////    h_EoC[i] -> SetLineColor(kGreen+2);
/////    
/////    sprintf(histoName, "Las_%d", i);
/////    h_Las[i] = new TH1F(histoName, histoName, 100, 0.5, 1.5);
/////  }
/////  
/////  
/////  
/////  // function definition
/////  TF1** f_EoP = new TF1*[nBins];
/////  TF1** f_EoC = new TF1*[nBins];
/////  
/////  
/////  
/////  // loop on the saved and sorted events
/////  std::cout << std::endl;
/////  std::cout << "***** Fill and fit histograms *****" << std::endl;
/////    
/////  vector<double> AveTime(nBins);
/////  vector<int> MinTime(nBins);
/////  vector<int> MaxTime(nBins);
/////   
/////  for(int ientry = 0; ientry < nEntries; ++ientry)
/////  {
/////    if( (ientry%100000 == 0) ) std::cout << "reading entry " << ientry << std::endl;
/////    
/////    if( isSavedEntries.at(ientry) == false ) continue;
/////    
/////    int iSaved = -1;
/////    for(iSaved = 0; iSaved < nSavePts; ++iSaved)
/////      if( ientry == sortedEntries[iSaved].entry ) break;
/////    
/////    int bin = -1;
/////    for(bin = 0; bin < nBins; ++bin)
/////      if( iSaved >= binEntryMax.at(bin) && iSaved < binEntryMax.at(bin+1) )
/////        break;
/////
/////    //std::cout << "bin = " << bin << "   iSaved = "<< iSaved << std::endl;
/////    
/////    ntu_DA->GetEntry(ientry);
/////        
/////    
/////    
/////    if( iSaved == binEntryMax.at(bin)+1 ) MinTime[bin] = timeStampHigh;
/////    if( iSaved == binEntryMax.at(bin+1)-1 ) MaxTime[bin] = timeStampHigh;
/////    AveTime[bin] += timeStampHigh;
/////    
/////    
/////    
/////    // fill the bins 
/////    (h_EoP[bin]) -> Fill(EoP/scLaserCorr);
/////    (h_EoC[bin]) -> Fill(EoP);
/////    
/////    (h_Las[bin]) -> Fill(scLaserCorr);    
/////    
/////    if(seedZside == 0)
/////      h_seedOccupancy_EB -> Fill(seedIeta,seedIphi);
/////    if(seedZside > 0)
/////      h_seedOccupancy_EEp -> Fill(seedIx,seedIy);
/////    if(seedZside < 0)
/////      h_seedOccupancy_EEm -> Fill(seedIx,seedIy);
/////  }
/////  
/////  for(int bin = 0; bin < nBins; ++bin)
/////  {
/////    AveTime[bin] = 1. * AveTime[bin] / (binEntryMax.at(bin+1)-binEntryMax.at(bin));
/////    //std::cout << date << " " << AveTime[i] << " " << MinTime[i] << " " << MaxTime[i] << std::endl;
/////  }
/////  
/////  
/////  // Define grpah and histograms
/////  TGraphAsymmErrors* g_fit   = new TGraphAsymmErrors();
/////  TGraphAsymmErrors* g_c_fit   = new TGraphAsymmErrors();
/////  g_fit->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00");
/////  g_fit->GetXaxis()->SetTimeDisplay(1);
/////  g_c_fit->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00");
/////  g_c_fit->GetXaxis()->SetTimeDisplay(1);
/////  
/////  
/////  int rebin = 4;
/////  if (strcmp(EBEE,"EB")==0) rebin = 2; 
/////  
/////  h_template -> Rebin(rebin*4);
/////  
/////  
/////  for(int i = 0; i < nBins; ++i)
/////  {
/////    h_EoP[i] -> Rebin(rebin*4);    
/////    h_EoC[i] -> Rebin(rebin*4);    
/////    
/////    
/////    
/////    //------------------------------------
/////    // Fill the graph for uncorrected data
/////    
/////    // define the fitting function
/////    // N.B. [0] * ( [1] * f( [1]*(x-[2]) ) )
/////
/////    histoFunc* templateHistoFunc = new histoFunc(h_template);
/////    char funcName[50];
/////    sprintf(funcName,"f_EoP_%d",i);
/////    f_EoP[i] = new TF1(funcName, templateHistoFunc, 0.7, 1.3, 3, "histoFunc");
/////    f_EoP[i] -> SetParName(0,"Norm"); 
/////    f_EoP[i] -> SetParName(1,"Scale factor"); 
/////    f_EoP[i] -> SetLineWidth(1); 
/////    f_EoP[i] -> SetNpx(10000);
/////    
/////    double xNorm = h_EoP[i]->GetEntries()/h_template->GetEntries() *
/////      h_EoP[i]->GetBinWidth(1)/h_template->GetBinWidth(1); 
/////    
/////    f_EoP[i] -> FixParameter(0, xNorm);
/////    f_EoP[i] -> SetParameter(1, 0.99);
/////    f_EoP[i] -> FixParameter(2, 0.);
/////    f_EoP[i] -> SetLineColor(kRed+2); 
/////    
/////    
/////    TFitResultPtr rp = h_EoP[i] -> Fit(funcName, "QNERLS+");
/////    int fStatus = rp;
/////    
/////    // fill the graph
/////    double eee = f_EoP[i]->GetParError(1); 
/////    if (fStatus!=4 && eee>0.1*h_template->GetRMS()/sqrt(evtsPerPoint))
/////    {
/////      float date = (float)AveTime[i]; 
/////      float dLow = (float)(AveTime[i]-MinTime[i]); 
/////      float dHig = (float)(MaxTime[i]-AveTime[i]);
/////      
/////      g_fit -> SetPoint(i,  date , 1./f_EoP[i]->GetParameter(1));
/////      g_fit -> SetPointError(i, dLow , dHig, eee, eee);
/////      if ( (date > t1) && (date < t2) )
/////        h_EoP_spread -> Fill(1./f_EoP[i]->GetParameter(1));
/////    }
/////    else
/////      std::cout << "Fitting uncorrected time bin: " << i << "   Fail status: " << fStatus << "   sigma: " << eee << endl;
/////    
/////    
/////    
/////    //----------------------------------
/////    // Fill the graph for corrected data
/////    
/////    // define the fitting function
/////    // N.B. [0] * ( [1] * f( [1]*(x-[2]) ) )
/////
/////    sprintf(funcName,"f_EoC_%d",i);
/////    f_EoC[i] = new TF1(funcName, templateHistoFunc, 0.7, 1.3, 3, "histoFunc");
/////    f_EoC[i] -> SetParName(0,"Norm"); 
/////    f_EoC[i] -> SetParName(1,"Scale factor"); 
/////    f_EoC[i] -> SetLineWidth(1); 
/////    f_EoC[i] -> SetNpx(10000);
/////    
/////    xNorm = h_EoC[i]->GetEntries()/h_template->GetEntries() *
/////            h_EoC[i]->GetBinWidth(1)/h_template->GetBinWidth(1); 
/////
/////    f_EoC[i] -> FixParameter(0, xNorm);
/////    f_EoC[i] -> SetParameter(1, 0.99);
/////    f_EoC[i] -> FixParameter(2, 0.);
/////    f_EoC[i] -> SetLineColor(kGreen+2); 
/////    
/////    
/////    TFitResultPtr rc = h_EoC[i] -> Fit(funcName, "QNERLS+");
/////    fStatus = rc;
/////    
/////    // fill the graph
/////    eee = f_EoC[i]->GetParError(1); 
/////    if (fStatus!=4 && eee>0.1*h_template->GetRMS()/sqrt(evtsPerPoint))
/////    {
/////      float date = (float)AveTime[i]; 
/////      float dLow = (float)(AveTime[i]-MinTime[i]); 
/////      float dHig = (float)(MaxTime[i]-AveTime[i]);
/////      
/////      g_c_fit -> SetPoint(i,  date , 1./f_EoC[i]->GetParameter(1));
/////      g_c_fit -> SetPointError(i, dLow , dHig , eee, eee);
/////      if ( (date > t1) && (date < t2) )
/////        h_EoC_spread -> Fill(1./f_EoC[i]->GetParameter(1));
/////    }
/////    else
/////      std::cout << "Fitting corrected time bin: " << i << "   Fail status: " << fStatus << "   sigma: " << eee << endl;
/////    
/////    
/////    
/////  }
/////  
/////  
/////  
/////  
/////  
/////  
/////  // Drawings
/////  TCanvas* c_seedOccupancy = new TCanvas("c_seedOccupancy","",100,100,900,500);
/////  c_seedOccupancy -> Divide(3,1);
/////  
/////  c_seedOccupancy -> cd(1);
/////  h_seedOccupancy_EB -> GetXaxis() -> SetTitle("i#eta");
/////  h_seedOccupancy_EB -> GetYaxis() -> SetTitle("i#phi");
/////  h_seedOccupancy_EB -> Draw("COLZ");
/////  
/////  c_seedOccupancy -> cd(2);
/////  h_seedOccupancy_EEp -> GetXaxis() -> SetTitle("ix");
/////  h_seedOccupancy_EEp -> GetYaxis() -> SetTitle("iy");
/////  h_seedOccupancy_EEp -> Draw("COLZ");
/////  
/////  c_seedOccupancy -> cd(3);
/////  h_seedOccupancy_EEm -> GetXaxis() -> SetTitle("ix");
/////  h_seedOccupancy_EEm -> GetYaxis() -> SetTitle("iy");
/////  h_seedOccupancy_EEm -> Draw("COLZ");
/////  
/////  
/////  
/////  //TPaveStats** s_EoP = new TPaveStats*[nBins];
/////  //TPaveStats** s_EoC = new TPaveStats*[nBins];
/////  //
/////  //TCanvas *c1[100]; 
/////  //for(int i = 0; i < nBins; ++i)
/////  //{
/////  //  char canvasName[50];
/////  //  if (i%6==0)
/////  //  {
/////  //    sprintf(canvasName, "Fits-%0d", i/6); 
/////  //    c1[i/6] = new TCanvas(canvasName, canvasName);
/////  //    c1[i/6] -> Divide(3,2);
/////  //  }
/////  //  c1[i/6] -> cd (i%6+1);
/////  //  
/////  //  h_EoP[i] -> GetXaxis() -> SetTitle("E/p");
/////  //  h_EoP[i] -> GetXaxis() -> SetRangeUser(0.5,1.5); 
/////  //  h_EoP[i] -> Draw("e");
/////  //  gPad->Update(); 
/////  //  s_EoP[i]= (TPaveStats*)(h_EoP[i]->GetListOfFunctions()->FindObject("stats"));
/////  //  s_EoP[i]->SetTextColor(kRed+2);
/////  //
/////  //  h_EoC[i] -> Draw("esames");
/////  //  gPad->Update(); 
/////  //  s_EoC[i]= (TPaveStats*)(h_EoC[i]->GetListOfFunctions()->FindObject("stats"));
/////  //  s_EoC[i]->SetY1NDC(0.59); //new x start position
/////  //  s_EoC[i]->SetY2NDC(0.79); //new x end position
/////  //  s_EoC[i]->SetTextColor(kGreen+2);
/////  //  s_EoC[i]->Draw("sames");
/////  //  
/////  //  f_EoP[i]->Draw("same");
/////  //  f_EoC[i]->Draw("same");
/////  //}
/////  
/////  
/////  
/////  
/////  
/////  
/////  TF1 pol0("pol0","pol0",t1,t2);
/////  pol0.SetLineColor(kGreen+2);
/////  pol0.SetLineWidth(2);
/////  pol0.SetLineStyle(2);
/////
/////  g_c_fit -> Fit("pol0","QNR");
/////  float emean = 0, eclean = 0 ;
/////  
/////  //float yscale = pol0.GetParameter(0); 
/////  float yscale = 1.;
/////
/////  for(int i = 0; i < nBins; ++i){
/////    eclean += g_c_fit->GetErrorYlow(i); 
/////    emean += g_c_fit->GetErrorYlow(i)*sqrt(pol0.GetChisquare()/pol0.GetNDF()); 
/////    // rescale to mean
/////    double x,y; 
/////    g_fit -> GetPoint(i,x,y); 
/////    g_fit -> SetPoint(i,x,y/yscale); 
/////    g_c_fit -> GetPoint(i,x,y); 
/////    g_c_fit -> SetPoint(i,x,y/yscale); 
/////  }
/////  std::cout << "Mean Error: " << emean/(float)nBins << " " << eclean/(float)nBins << std::endl; 
/////  g_c_fit -> Fit("pol0","QR+");
/////  
/////  
/////  
/////  
/////  
/////  
/////  // Final plots
/////  TCanvas* cplot = new TCanvas("cplot", "history plot",100,100,1000,500);
/////  cplot->cd();
/////
/////  TPad *cLeft  = new TPad("pad_0","pad_0",0.00,0.00,0.75,1.00);
/////  TPad *cRight = new TPad("pad_1","pad_1",0.75,0.00,1.00,1.00);
/////
/////  cLeft->SetLeftMargin(0.15); 
/////  cLeft->SetRightMargin(0.025); 
/////  cRight->SetLeftMargin(0.025); 
/////
/////  cLeft->Draw();
/////  cRight->Draw();
/////
/////  float tYoffset = 1.5; 
/////  float labSize = 0.04;
/////  float labSize2 = 0.07;
/////
/////  cLeft->cd(); 
/////
/////  cLeft->SetGridx();
/////  cLeft->SetGridy();
/////  
/////  TH1F *hPad = (TH1F*)gPad->DrawFrame(t1,0.9,t2,1.05);
/////  hPad->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00");
/////  hPad->GetXaxis()->SetTimeDisplay(1);
/////  hPad->GetXaxis() -> SetRangeUser(MinTime[0]-43200,MaxTime[nBins-1]+43200);
/////  hPad->GetXaxis()->SetTitle("date");
/////  hPad->GetYaxis()->SetTitle("Relative E/p scale"); 
/////  hPad->GetYaxis()->SetTitleOffset(tYoffset);
/////  hPad->GetXaxis()->SetLabelSize(labSize);
/////  hPad->GetXaxis()->SetTitleSize(labSize);
/////  hPad->GetYaxis()->SetLabelSize(labSize);
/////  hPad->GetYaxis()->SetTitleSize(labSize);
/////  
/////  if ( strcmp(EBEE,"EB")==0 )
/////  {  
/////    hPad -> SetMinimum(0.965);
/////    hPad -> SetMaximum(1.010);
/////  }
/////  else 
/////  {  
/////    hPad -> SetMinimum(0.880);
/////    hPad -> SetMaximum(1.030);
/////  }
/////  
/////  // draw history plot
/////  g_fit -> SetMarkerStyle(20);
/////  g_fit -> SetMarkerSize(0.75);
/////  g_fit -> SetMarkerColor(kRed+2);
/////  g_fit -> SetLineColor(kRed+2);
/////  g_fit -> Draw("P");
/////  g_c_fit -> SetMarkerStyle(20);
/////  g_c_fit -> SetMarkerColor(kGreen+2);
/////  g_c_fit -> SetLineColor(kGreen+2);
/////  g_c_fit -> SetMarkerSize(0.75);
/////  g_c_fit -> Draw("P,same");
/////  
/////  
/////  
/////  cRight -> cd();
/////  
/////  TPaveStats* s_EoP_spread = new TPaveStats();
/////  TPaveStats* s_EoC_spread = new TPaveStats();
/////  
/////  
/////  h_EoC_spread -> SetFillStyle(3001);
/////  h_EoC_spread -> SetFillColor(kGreen+2);
/////  h_EoC_spread->GetYaxis()->SetLabelSize(labSize2);
/////  h_EoC_spread->GetYaxis()->SetTitleSize(labSize2);
/////  h_EoC_spread->GetYaxis()->SetNdivisions(505);
/////  h_EoC_spread->GetYaxis()->SetLabelOffset(-0.02);
/////  h_EoC_spread->GetXaxis()->SetLabelOffset(1000);
/////
/////  h_EoC_spread -> Draw("hbar");
/////  gPad -> Update();
/////
/////  s_EoC_spread = (TPaveStats*)(h_EoC_spread->GetListOfFunctions()->FindObject("stats"));
/////  s_EoC_spread ->SetTextColor(kGreen+2);
/////  s_EoC_spread ->SetTextSize(0.06);
/////  s_EoC_spread->SetX1NDC(0.49); //new x start position
/////  s_EoC_spread->SetX2NDC(0.99); //new x end position
/////  s_EoC_spread->SetY1NDC(0.875); //new x start position
/////  s_EoC_spread->SetY2NDC(0.990); //new x end position
/////  s_EoC_spread -> SetOptStat(1100);
/////  s_EoC_spread -> Draw("sames");
/////
/////  h_EoP_spread -> SetFillStyle(3001);
/////  h_EoP_spread -> SetFillColor(kRed+2);
/////  h_EoP_spread -> Draw("hbarsames");
/////  gPad -> Update();
/////  s_EoP_spread = (TPaveStats*)(h_EoP_spread->GetListOfFunctions()->FindObject("stats"));
/////  s_EoP_spread->SetX1NDC(0.49); //new x start position
/////  s_EoP_spread->SetX2NDC(0.99); //new x end position
/////  s_EoP_spread->SetY1NDC(0.750); //new x start position
/////  s_EoP_spread->SetY2NDC(0.875); //new x end position
/////  s_EoP_spread ->SetOptStat(1100);
/////  s_EoP_spread ->SetTextColor(kRed+2);
/////  s_EoP_spread ->SetTextSize(0.06);
/////  s_EoP_spread -> Draw("sames");
/////  
/////  
/////  //TFile* o = new TFile("trisCheckStabilityHistos.root","RECREATE");
/////  //o -> cd();
/////  //
/////  //g_fit -> Write("g_fit");
/////  //g_c_fit -> Write("g_c_fit");
/////  //
/////  //o -> Close();
}
int main(int argc, char** argv)
{
  // Set style options
  setTDRStyle();
  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);
  gStyle->SetOptTitle(0); 
  gStyle->SetOptStat(1110); 
  gStyle->SetOptFit(1); 
  
  // Set fitting options
  TVirtualFitter::SetDefaultFitter("Fumili2");
  
  
  
  
  
  
  //-----------------
  // Input parameters
  
  std::cout << "\n***************************************************************************************************************************" << std::endl;
  std::cout << "arcg: " << argc << std::endl;
  char* EBEE = argv[1];
  int evtsPerPoint = atoi(argv[2]);
  int useRegression = atoi(argv[3]);
  std::string dayMin = "";
  std::string dayMax = "";
  std::string dayMinLabel = "";
  std::string dayMaxLabel = "";
  float absEtaMin = -1.;
  float absEtaMax = -1.;
  int IetaMin = -1;
  int IetaMax = -1;
  int IphiMin = -1;
  int IphiMax = -1;
  if(argc >= 5)
  {
    dayMin = std::string(argv[4])+" "+std::string(argv[5])+" "+std::string(argv[6]);
    dayMax = std::string(argv[7])+" "+std::string(argv[8])+" "+std::string(argv[9]);
    dayMinLabel = std::string(argv[4])+"_"+std::string(argv[5])+"_"+std::string(argv[6]);
    dayMaxLabel = std::string(argv[7])+"_"+std::string(argv[8])+"_"+std::string(argv[9]);
    
    t1 = dateToInt(dayMin);
    t2 = dateToInt(dayMax);
  }
  if(argc >= 11)
  {
    yMIN = atof(argv[10]);
    yMAX = atof(argv[11]);
  }
  if(argc >= 13)
  {
    absEtaMin = atof(argv[12]);
    absEtaMax = atof(argv[13]);
  }
  if(argc >= 15)
  {
    IetaMin = atoi(argv[14]);
    IetaMax = atoi(argv[15]);
    IphiMin = atoi(argv[16]);
    IphiMax = atoi(argv[17]);
  }
  
  std::cout << "EBEE: "          << EBEE          << std::endl;
  std::cout << "evtsPerPoint: "  << evtsPerPoint  << std::endl;
  std::cout << "useRegression: " << useRegression << std::endl;
  std::cout << "dayMin: "        << dayMin        << std::endl;
  std::cout << "dayMax: "        << dayMax        << std::endl;
  std::cout << "yMin: "          << yMIN          << std::endl;
  std::cout << "yMax: "          << yMAX          << std::endl;
  std::cout << "absEtaMin: "     << absEtaMin     << std::endl;
  std::cout << "absEtaMax: "     << absEtaMax     << std::endl;
  std::cout << "IetaMin: "       << IetaMin       << std::endl;
  std::cout << "IetaMax: "       << IetaMax       << std::endl;
  std::cout << "IphiMin: "       << IphiMin       << std::endl;
  std::cout << "IphiMax: "       << IphiMax       << std::endl;
  
  
  
  
  
  
  //-------------------
  // Define in/outfiles
  
  std::string folderName = std::string(EBEE) + "_" + dayMinLabel + "_" + dayMaxLabel;
  if( (absEtaMin != -1.) && (absEtaMax != -1.) )
  {
    char absEtaBuffer[50];
    sprintf(absEtaBuffer,"_%.2f-%.2f",absEtaMin,absEtaMax);
    folderName += std::string(absEtaBuffer);
  } 
  
  if( (IetaMin != -1.) && (IetaMax != -1.) && (IphiMin != -1.) && (IphiMax != -1.) )
  {
    char absEtaBuffer[50];
    sprintf(absEtaBuffer,"_Ieta_%d-%d_Iphi_%d-%d",IetaMin,IetaMax,IphiMin,IphiMax);
    folderName += std::string(absEtaBuffer);
  } 
  
  gSystem->mkdir(folderName.c_str());
  TFile* o = new TFile((folderName+"/"+folderName+"_histos.root").c_str(),"RECREATE");
  
  
  
  // Get trees
  std::cout << std::endl;
  
  TChain* ntu_DA = new TChain("simpleNtupleEoverP/SimpleNtupleEoverP");
  FillChain(ntu_DA,"inputDATA.txt");
  std::cout << "     DATA: " << std::setw(8) << ntu_DA->GetEntries() << " entries" << std::endl;
  
  TChain* ntu_MC = new TChain("simpleNtupleEoverP/SimpleNtupleEoverP");
  FillChain(ntu_MC,"inputMC.txt");
  std::cout << "REFERENCE: " << std::setw(8) << ntu_MC->GetEntries() << " entries" << std::endl;
  
  if (ntu_DA->GetEntries() == 0 || ntu_MC->GetEntries() == 0 )
  {
    std::cout << "Error: At least one file is empty" << std::endl; 
    return -1;
  }
  
  
  
  // Set branch addresses
  int runId;
  int timeStampHigh;
  int PV_n;
  float scLaserCorr, seedLaserAlpha, EoP, scEta, scPhi, scE, ES, P;
  int seedIeta, seedIphi, seedIx, seedIy, seedZside;
  
  ntu_DA->SetBranchStatus("*",0);
  ntu_DA->SetBranchStatus("runId",1);  
  ntu_DA->SetBranchStatus("timeStampHigh",1);
  ntu_DA->SetBranchStatus("PV_n",1);
  ntu_DA->SetBranchStatus("ele1_scLaserCorr",1);
  ntu_DA->SetBranchStatus("ele1_seedLaserAlpha",1);
  ntu_DA->SetBranchStatus("ele1_EOverP",1);
  ntu_DA->SetBranchStatus("ele1_scEta",1);
  ntu_DA->SetBranchStatus("ele1_scPhi",1);
  ntu_DA->SetBranchStatus("ele1_scE",1);
  ntu_DA->SetBranchStatus("ele1_scE_regression",1);
  ntu_DA->SetBranchStatus("ele1_scE",1);
  ntu_DA->SetBranchStatus("ele1_es",1);
  ntu_DA->SetBranchStatus("ele1_tkP",1);
  ntu_DA->SetBranchStatus("ele1_seedIeta",1);
  ntu_DA->SetBranchStatus("ele1_seedIphi",1);
  ntu_DA->SetBranchStatus("ele1_seedIx",1);
  ntu_DA->SetBranchStatus("ele1_seedIy",1);
  ntu_DA->SetBranchStatus("ele1_seedZside",1);
    
  ntu_DA->SetBranchAddress("runId", &runId);  
  ntu_DA->SetBranchAddress("timeStampHigh", &timeStampHigh);
  ntu_DA->SetBranchAddress("PV_n", &PV_n);
  ntu_DA->SetBranchAddress("ele1_scLaserCorr", &scLaserCorr);
  ntu_DA->SetBranchAddress("ele1_seedLaserAlpha", &seedLaserAlpha);
  ntu_DA->SetBranchAddress("ele1_EOverP", &EoP);
  ntu_DA->SetBranchAddress("ele1_scEta", &scEta);
  ntu_DA->SetBranchAddress("ele1_scPhi", &scPhi);
  if( useRegression < 1 )
    ntu_DA->SetBranchAddress("ele1_scE", &scE);
  else
    ntu_DA->SetBranchAddress("ele1_scE_regression", &scE);
  ntu_DA->SetBranchAddress("ele1_scE", &scE);
  ntu_DA->SetBranchAddress("ele1_es", &ES);
  ntu_DA->SetBranchAddress("ele1_tkP", &P);
  ntu_DA->SetBranchAddress("ele1_seedIeta", &seedIeta);
  ntu_DA->SetBranchAddress("ele1_seedIphi", &seedIphi);
  ntu_DA->SetBranchAddress("ele1_seedIx", &seedIx);
  ntu_DA->SetBranchAddress("ele1_seedIy", &seedIy);
  ntu_DA->SetBranchAddress("ele1_seedZside", &seedZside);
  
  
  ntu_MC->SetBranchStatus("*",0);
  ntu_MC->SetBranchStatus("runId",1);
  ntu_MC->SetBranchStatus("PV_n",1);
  ntu_MC->SetBranchStatus("ele1_scEta",1);
  ntu_MC->SetBranchStatus("ele1_EOverP",1);
  ntu_MC->SetBranchStatus("ele1_scE",1);
  ntu_MC->SetBranchStatus("ele1_scE_regression",1);
  ntu_MC->SetBranchStatus("ele1_es",1);
  ntu_MC->SetBranchStatus("ele1_tkP",1);
  ntu_MC->SetBranchStatus("ele1_seedIeta",1);
  ntu_MC->SetBranchStatus("ele1_seedIphi",1);
  ntu_MC->SetBranchStatus("ele1_seedIx",1);
  ntu_MC->SetBranchStatus("ele1_seedIy",1);
  ntu_MC->SetBranchStatus("ele1_seedZside",1);
  
  ntu_MC->SetBranchAddress("runId", &runId);  
  ntu_MC->SetBranchAddress("PV_n", &PV_n);
  ntu_MC->SetBranchAddress("ele1_scEta", &scEta);
  ntu_MC->SetBranchAddress("ele1_EOverP", &EoP);
  if( useRegression < 1 )
    ntu_MC->SetBranchAddress("ele1_scE", &scE);
  else
    ntu_MC->SetBranchAddress("ele1_scE_regression", &scE);
  ntu_MC->SetBranchAddress("ele1_es", &ES);
  ntu_MC->SetBranchAddress("ele1_tkP", &P);
  ntu_MC->SetBranchAddress("ele1_seedIeta", &seedIeta);
  ntu_MC->SetBranchAddress("ele1_seedIphi", &seedIphi);
  ntu_MC->SetBranchAddress("ele1_seedIx", &seedIx);
  ntu_MC->SetBranchAddress("ele1_seedIy", &seedIy);
  ntu_MC->SetBranchAddress("ele1_seedZside", &seedZside);
  
  
  
  
  
  
  //--------------------------------------------------------
  // Define PU correction (to be used if useRegression == 0)
  
  // corr = p0 + p1 * PV_n
  float p0_EB;
  float p1_EB;
  float p0_EE;
  float p1_EE;
  
  if( useRegression == 0 )
  {
    //2012 EB
    p0_EB = 0.9991;
    p1_EB = 0.0001635;
    //2012 EE
    p0_EE = 0.9968;
    p1_EE = 0.001046;
  }
  else
  {
    //2012 EB
    p0_EB = 1.001;
    p1_EB = -0.000143;
    //2012 EE
    p0_EE = 1.00327;
    p1_EE = -0.000432;
  }
  
  float p0 = -1.;
  float p1 = -1.;
  
  if( strcmp(EBEE,"EB") == 0 )
  {
    p0 = p0_EB;
    p1 = p1_EB;
  }
  else
  {
    p0 = p0_EE;
    p1 = p1_EE;
  }
  
  
  
  
  
  
  //---------------------------------
  // Build the reference distribution
  
  std::cout << std::endl;
  std::cout << "***** Build reference for " << EBEE << " *****" << std::endl;
  
  TH1F* h_template = new TH1F("template", "", 2000, 0., 5.);
  
  for(int ientry = 0; ientry < ntu_MC->GetEntries(); ++ientry)
  {
    if( (ientry%100000 == 0) ) std::cout << "reading MC entry " << ientry << "\r" << std::flush;
    ntu_MC->GetEntry(ientry);
    
    // selections
    if( (strcmp(EBEE,"EB") == 0) && (fabs(scEta) > 1.45) )                    continue; // barrel
    if( (strcmp(EBEE,"EE") == 0) && (fabs(scEta) < 1.47 || fabs(scEta)>2.7) ) continue; // endcap

    if( (absEtaMin != -1.) && (absEtaMax != -1.) )
    {
      if( (fabs(scEta) < absEtaMin) || (fabs(scEta) > absEtaMax) ) continue;
    }
    
    if( (IetaMin != -1.) && (IetaMax != -1.) && (IphiMin != -1.) && (IphiMax != -1.) )
    {
      if( (seedIeta < IetaMin) || (seedIeta > IetaMax) ) continue;
      if( (seedIphi < IphiMin) || (seedIphi > IphiMax) ) continue;
    }
    
    // PU correction
    float PUCorr = (p0 + p1*PV_n);
    //std::cout << "p0: " << p0  << "   p1: " << p1 << "   PV_n: " << PV_n << std::endl;
    
    // fill the template histogram
    h_template -> Fill( (scE-ES)/(P-ES) / PUCorr );
  }
  
  std::cout << "Reference built for " << EBEE << " - " << h_template->GetEntries() << " events" << std::endl;
  
  
  
  
  
  
  //---------------------
  // Loop and sort events
  
  std::cout << std::endl;
  std::cout << "***** Sort events and define bins *****" << std::endl;
  
  int nEntries = ntu_DA -> GetEntriesFast(); 
  int nSavePts = 0; 
  std::vector<bool> isSavedEntries(nEntries);
  std::vector<Sorter> sortedEntries;
  std::vector<int> timeStampFirst;
  
  for(int ientry = 0; ientry < nEntries; ++ientry)
  {
    ntu_DA -> GetEntry(ientry);
    isSavedEntries.at(ientry) = false;
    
    // selections
    if( (strcmp(EBEE,"EB") == 0) && (fabs(scEta) > 1.45) )                    continue; // barrel
    if( (strcmp(EBEE,"EE") == 0) && (fabs(scEta) < 1.47 || fabs(scEta)>2.7) ) continue; // endcap
    
    if( (absEtaMin != -1.) && (absEtaMax != -1.) )
    {
      if( (fabs(scEta) < absEtaMin) || (fabs(scEta) > absEtaMax) ) continue;
    }
    
    if( (IetaMin != -1.) && (IetaMax != -1.) && (IphiMin != -1.) && (IphiMax != -1.) )
    {
      if( (seedIeta < IetaMin) || (seedIeta > IetaMax) ) continue;
      if( (seedIphi < IphiMin) || (seedIphi > IphiMax) ) continue;
    }
    
    if( timeStampHigh < t1 ) continue;
    if( timeStampHigh > t2 ) continue;
    
    if( scLaserCorr <= 0. ) continue;
    
    isSavedEntries.at(ientry) = true;
    
    
    // fill sorter
    Sorter dummy;
    dummy.time = timeStampHigh;
    dummy.entry = ientry;
    sortedEntries.push_back(dummy);
    
    ++nSavePts;
  }
  
  // sort events
  std::sort(sortedEntries.begin(),sortedEntries.end(),Sorter());
  std::cout << "Data sorted in " << EBEE << " - " << nSavePts << " events" << std::endl;
  
  std::map<int,int> antiMap;
  for(unsigned int iSaved = 0; iSaved < sortedEntries.size(); ++iSaved)
    antiMap[sortedEntries.at(iSaved).entry] = iSaved;
  
  
  //---------------------
  // Loop and define bins
  
  // "wide" bins - find events with time separation bigger than 1 day
  int nWideBins = 1;
  std::vector<int> wideBinEntryMax;
  int timeStampOld = -1;
  
  wideBinEntryMax.push_back(0);  
  for(int iSaved = 0; iSaved < nSavePts; ++iSaved)
  {
    if( iSaved%100000 == 0 ) std::cout << "reading saved entry " << iSaved << "\r" << std::flush;
    ntu_DA->GetEntry(sortedEntries[iSaved].entry);  
    
    if( iSaved == 0 )
    {
      timeStampOld = timeStampHigh;
      continue;
    }
    
    if( (timeStampHigh-timeStampOld)/3600. > timeLapse )
    {
      ++nWideBins;
      wideBinEntryMax.push_back(iSaved-1);
    }
    
    timeStampOld = timeStampHigh;
  }
  std::cout << std::endl;
  wideBinEntryMax.push_back(nSavePts);
  
  
  // bins with approximatively evtsPerPoint events per bin
  int nBins = 0;
  std::vector<int> binEntryMax;
  
  binEntryMax.push_back(0);
  for(int wideBin = 0; wideBin < nWideBins; ++wideBin)
  {
    int nTempBins = std::max(1,int( (wideBinEntryMax.at(wideBin+1)-wideBinEntryMax.at(wideBin))/evtsPerPoint ));
    int nTempBinEntries = int( (wideBinEntryMax.at(wideBin+1)-wideBinEntryMax.at(wideBin))/nTempBins );
    
    for(int tempBin = 0; tempBin < nTempBins; ++tempBin)
    {
      ++nBins;
      if( tempBin < nTempBins - 1 )
        binEntryMax.push_back( wideBinEntryMax.at(wideBin) + (tempBin+1)*nTempBinEntries );
      else
        binEntryMax.push_back( wideBinEntryMax.at(wideBin+1) );
    }
  }
  
  std::cout << "nBins = " << nBins << std::endl;
  //for(int bin = 0; bin < nBins; ++bin)
  //  std::cout << "bin: " << bin
  //            << "   entry min: " << setw(6) << binEntryMax.at(bin)
  //            << "   entry max: " << setw(6) << binEntryMax.at(bin+1)
  //            << "   events: "    << setw(6) << binEntryMax.at(bin+1)-binEntryMax.at(bin)
  //            << std::endl;
  
  
  
  
  
  
  //---------------------
  // histogram definition
  
  TH1F* h_scOccupancy_eta  = new TH1F("h_scOccupancy_eta","", 298, -2.6, 2.6);
  TH1F* h_scOccupancy_phi  = new TH1F("h_scOccupancy_phi","", 363, -3.1765, 3.159);
  SetHistoStyle(h_scOccupancy_eta);
  SetHistoStyle(h_scOccupancy_phi);
  
  TH2F* h_seedOccupancy_EB  = new TH2F("h_seedOccupancy_EB","",  171, -85., 86., 361,   0.,361.);
  TH2F* h_seedOccupancy_EEp = new TH2F("h_seedOccupancy_EEp","", 101,   0.,101., 100,   0.,101.);
  TH2F* h_seedOccupancy_EEm = new TH2F("h_seedOccupancy_EEm","", 101,   0.,101., 100,   0.,101.);
  SetHistoStyle(h_seedOccupancy_EB);
  SetHistoStyle(h_seedOccupancy_EEp);
  SetHistoStyle(h_seedOccupancy_EEm);
  
  TH1F* h_EoP_spread = new TH1F("h_EoP_spread","",100,yMIN,yMAX);
  TH1F* h_EoC_spread = new TH1F("h_EoC_spread","",100,yMIN,yMAX);
  TH1F* h_EoP_spread_run = new TH1F("h_EoP_spread_run","",100,yMIN,yMAX);
  TH1F* h_EoC_spread_run = new TH1F("h_EoC_spread_run","",100,yMIN,yMAX);
  SetHistoStyle(h_EoP_spread,"EoP");
  SetHistoStyle(h_EoC_spread,"EoC");
  SetHistoStyle(h_EoP_spread_run,"EoP");
  SetHistoStyle(h_EoC_spread_run,"EoC");
  
  TH1F* h_EoP_chi2 = new TH1F("h_EoP_chi2","",50,0.,5.);
  TH1F* h_EoC_chi2 = new TH1F("h_EoC_chi2","",50,0.,5.);
  SetHistoStyle(h_EoP_chi2,"EoP");
  SetHistoStyle(h_EoC_chi2,"EoC");  
  
  TH1F** h_EoP = new TH1F*[nBins];
  TH1F** h_EoC = new TH1F*[nBins];
  TH1F** h_Las = new TH1F*[nBins];
  TH1F** h_Tsp = new TH1F*[nBins];
  TH1F** h_Cvl = new TH1F*[nBins];
  
  for(int i = 0; i < nBins; ++i)
  {
    char histoName[80];
    
    sprintf(histoName, "EoP_%d", i);
    h_EoP[i] = new TH1F(histoName, histoName, 2000, 0., 5.);
    SetHistoStyle(h_EoP[i],"EoP");
    
    sprintf(histoName, "EoC_%d", i);
    h_EoC[i] = new TH1F(histoName, histoName, 2000, 0., 5.);
    SetHistoStyle(h_EoC[i],"EoC");
    
    sprintf(histoName, "Las_%d", i);
    h_Las[i] = new TH1F(histoName, histoName, 500, 0.5, 1.5);
    
    sprintf(histoName, "Tsp_%d", i);
    h_Tsp[i] = new TH1F(histoName, histoName, 500, 0.5, 1.5);
  }
  
  
  // function definition
  TF1** f_EoP = new TF1*[nBins];
  TF1** f_EoC = new TF1*[nBins];
  
  
  // graphs definition
  TGraphAsymmErrors* g_fit   = new TGraphAsymmErrors();
  TGraphAsymmErrors* g_c_fit = new TGraphAsymmErrors();
  
  TGraphAsymmErrors* g_fit_run   = new TGraphAsymmErrors();
  TGraphAsymmErrors* g_c_fit_run = new TGraphAsymmErrors();  
  
  TGraph* g_las = new TGraph();
  
  TGraphErrors* g_LT = new TGraphErrors();
  
  g_fit->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00");
  g_fit->GetXaxis()->SetTimeDisplay(1);
  g_c_fit->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00");
  g_c_fit->GetXaxis()->SetTimeDisplay(1);
  g_las->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00");
  g_las->GetXaxis()->SetTimeDisplay(1);
  g_LT->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00");
  g_LT->GetXaxis()->SetTimeDisplay(1);
    
  
  
  
  
  
  //------------------------------------
  // loop on the saved and sorted events
  
  std::cout << std::endl;
  std::cout << "***** Fill and fit histograms *****" << std::endl;

  std::vector<int> Entries(nBins);  
  std::vector<double> AveTime(nBins);
  std::vector<int> MinTime(nBins);
  std::vector<int> MaxTime(nBins);
  std::vector<double> AveRun(nBins);    
  std::vector<int> MinRun(nBins);
  std::vector<int> MaxRun(nBins);
  std::vector<double> AveLT(nBins);
  std::vector<double> AveLT2(nBins);
    
  int iSaved = -1;
  for(int ientry = 0; ientry < nEntries; ++ientry)
  {
    if( (ientry%100000 == 0) ) std::cout << "reading entry " << ientry << "\r" << std::flush;
    
    if( isSavedEntries.at(ientry) == false ) continue;
    
    ++iSaved;
    
    int iSaved = antiMap[ientry];
    int bin = -1;
    for(bin = 0; bin < nBins; ++bin)
      if( iSaved >= binEntryMax.at(bin) && iSaved < binEntryMax.at(bin+1) )
	break;
    
    //std::cout << "bin = " << bin << "   iSaved = "<< iSaved << std::endl;
    ntu_DA->GetEntry(ientry);
    
    
    
    Entries[bin] += 1;
    
    if( iSaved == binEntryMax.at(bin)+1 )   MinTime[bin] = timeStampHigh;
    if( iSaved == binEntryMax.at(bin+1)-1 ) MaxTime[bin] = timeStampHigh;
    AveTime[bin] += timeStampHigh;
    
    if( iSaved == binEntryMax.at(bin)+1 )   MinRun[bin] = runId;
    if( iSaved == binEntryMax.at(bin+1)-1 ) MaxRun[bin] = runId;
    AveRun[bin] += runId;
    
    float LT = (-1. / seedLaserAlpha * log(scLaserCorr));
    AveLT[bin] += LT;
    AveLT2[bin] += LT*LT;
    
    // PU correction
    float PUCorr = (p0 + p1*PV_n);
    
    // fill the histograms
    (h_EoP[bin]) -> Fill( (scE-ES)/(P-ES) / scLaserCorr / PUCorr);
    (h_EoC[bin]) -> Fill( (scE-ES)/(P-ES) / PUCorr );
    
    (h_Las[bin]) -> Fill(scLaserCorr);
    (h_Tsp[bin]) -> Fill(1./scLaserCorr);
    
    h_scOccupancy_eta -> Fill(scEta);
    h_scOccupancy_phi -> Fill(scPhi);
    if(seedZside == 0)
      h_seedOccupancy_EB -> Fill(seedIeta,seedIphi);
    if(seedZside > 0)
      h_seedOccupancy_EEp -> Fill(seedIx,seedIy);
    if(seedZside < 0)
      h_seedOccupancy_EEm -> Fill(seedIx,seedIy);
  }
  
  for(int bin = 0; bin < nBins; ++bin)
  {
    AveTime[bin] = 1. * AveTime[bin] / (binEntryMax.at(bin+1)-binEntryMax.at(bin));
    AveRun[bin]  = 1. * AveRun[bin]  / (binEntryMax.at(bin+1)-binEntryMax.at(bin));
    AveLT[bin]   = 1. * AveLT[bin]   / (binEntryMax.at(bin+1)-binEntryMax.at(bin));
    AveLT2[bin]  = 1. * AveLT2[bin]  / (binEntryMax.at(bin+1)-binEntryMax.at(bin));
    //std::cout << date << " " << AveTime[i] << " " << MinTime[i] << " " << MaxTime[i] << std::endl;
  }
  
  
  
  
  
  
  int rebin = 2;
  if( strcmp(EBEE,"EE") == 0 ) rebin *= 2;
  
  h_template -> Rebin(rebin);
  
  
  
  float EoP_scale = 0.;
  float EoP_err = 0.;
  int   EoP_nActiveBins = 0;
  
  float EoC_scale = 0.;
  float EoC_err = 0.;
  int   EoC_nActiveBins = 0;
  
  float LCInv_scale = 0;
  
  std::vector<int> validBins;
  for(int i = 0; i < nBins; ++i)
  {
    bool isValid = true;
    
    h_EoP[i] -> Rebin(rebin);
    h_EoC[i] -> Rebin(rebin);
    
    
    
    //------------------------------------
    // Fill the graph for uncorrected data
    
    // define the fitting function
    // N.B. [0] * ( [1] * f( [1]*(x-[2]) ) )
    
    //o -> cd();
    char convolutionName[50];
    sprintf(convolutionName,"h_convolution_%d",i);
    //h_Cvl[i] = ConvoluteTemplate(std::string(convolutionName),h_template,h_Las[i],32768,-5.,5.);
    h_Cvl[i] = MellinConvolution(std::string(convolutionName),h_template,h_Tsp[i]);
    
    histoFunc* templateHistoFunc = new histoFunc(h_template);
    histoFunc* templateConvolutedHistoFunc = new histoFunc(h_Cvl[i]);
    char funcName[50];

    sprintf(funcName,"f_EoP_%d",i);
    
    if( strcmp(EBEE,"EB") == 0 )
      f_EoP[i] = new TF1(funcName, templateConvolutedHistoFunc, 0.8*(h_Tsp[i]->GetMean()), 1.4*(h_Tsp[i]->GetMean()), 3, "histoFunc");
    else
      f_EoP[i] = new TF1(funcName, templateConvolutedHistoFunc, 0.75*(h_Tsp[i]->GetMean()), 1.5*(h_Tsp[i]->GetMean()), 3, "histoFunc");
    
    f_EoP[i] -> SetParName(0,"Norm"); 
    f_EoP[i] -> SetParName(1,"Scale factor"); 
    f_EoP[i] -> SetLineWidth(1); 
    f_EoP[i] -> SetNpx(10000);
    
    double xNorm = h_EoP[i]->GetEntries()/h_template->GetEntries() *
      h_EoP[i]->GetBinWidth(1)/h_template->GetBinWidth(1); 
    
    f_EoP[i] -> FixParameter(0, xNorm);
    f_EoP[i] -> SetParameter(1, 1.);
    f_EoP[i] -> FixParameter(2, 0.);
    f_EoP[i] -> SetLineColor(kRed+2); 
    
    int fStatus = 0;
    int nTrials = 0;
    TFitResultPtr rp;
    
    rp = h_EoP[i] -> Fit(funcName, "QERLS+");
    while( (fStatus != 0) && (nTrials < 10) )
    {
      rp = h_EoP[i] -> Fit(funcName, "QERLS+");
      fStatus = rp;
      if(fStatus == 0) break;
      ++nTrials;
    }
    
    // fill the graph
    double eee = f_EoP[i]->GetParError(1);
    //float k    = f_EoP[i]->GetParameter(1);
    float k    = f_EoP[i]->GetParameter(1) / h_Tsp[i]->GetMean(); //needed when using mellin's convolution 
    
    if( (h_EoP[i]->GetEntries() > 3) && (fStatus == 0) && (eee > 0.05*h_template->GetRMS()/sqrt(evtsPerPoint)) )
    {
      float date = (float)AveTime[i];
      float dLow = (float)(AveTime[i]-MinTime[i]); 
      float dHig = (float)(MaxTime[i]-AveTime[i]);
      float run = (float)AveRun[i];
      float rLow = (float)(AveRun[i]-MinRun[i]); 
      float rHig = (float)(MaxRun[i]-AveRun[i]);
      
      g_fit -> SetPoint(i,  date , 1./k);
      g_fit -> SetPointError(i, dLow , dHig, eee/k/k, eee/k/k);
      
      g_fit_run -> SetPoint(i,  run , 1./k);
      g_fit_run -> SetPointError(i, rLow , rHig, eee/k/k, eee/k/k);
      
      h_EoP_chi2 -> Fill(f_EoP[i]->GetChisquare()/f_EoP[i]->GetNDF());
      
      EoP_scale += 1./k;
      EoP_err += eee/k/k;
      ++EoP_nActiveBins;
    }
    else
    {
      std::cout << "Fitting uncorrected time bin: " << i << "   Fail status: " << fStatus << "   sigma: " << eee << std::endl;
      isValid = false;
    }  
    
    //----------------------------------
    // Fill the graph for corrected data
    
    // define the fitting function
    // N.B. [0] * ( [1] * f( [1]*(x-[2]) ) )

    sprintf(funcName,"f_EoC_%d",i);
    if( strcmp(EBEE,"EB") == 0 )
      f_EoC[i] = new TF1(funcName, templateHistoFunc, 0.8, 1.4, 3, "histoFunc");
    else
      f_EoC[i] = new TF1(funcName, templateHistoFunc, 0.75, 1.5, 3, "histoFunc");
    f_EoC[i] -> SetParName(0,"Norm"); 
    f_EoC[i] -> SetParName(1,"Scale factor"); 
    f_EoC[i] -> SetLineWidth(1); 
    f_EoC[i] -> SetNpx(10000);
    
    xNorm = h_EoC[i]->GetEntries()/h_template->GetEntries() *
            h_EoC[i]->GetBinWidth(1)/h_template->GetBinWidth(1); 

    f_EoC[i] -> FixParameter(0, xNorm);
    f_EoC[i] -> SetParameter(1, 0.99);
    f_EoC[i] -> FixParameter(2, 0.);
    f_EoC[i] -> SetLineColor(kGreen+2); 
    
    
    rp = h_EoC[i] -> Fit(funcName, "QERLS+");
    fStatus = rp;
    nTrials = 0;
    while( (fStatus != 0) && (nTrials < 10) )
    {
      rp = h_EoC[i] -> Fit(funcName, "QERLS+");
      fStatus = rp;
      if(fStatus == 0) break;
      ++nTrials;
    }
    
    // fill the graph
    k   = f_EoC[i]->GetParameter(1);
    eee = f_EoC[i]->GetParError(1); 
    
    if( (h_EoC[i]->GetEntries() > 10) && (fStatus == 0) && (eee > 0.05*h_template->GetRMS()/sqrt(evtsPerPoint)) )
    {
      float date = (float)AveTime[i]; 
      float dLow = (float)(AveTime[i]-MinTime[i]); 
      float dHig = (float)(MaxTime[i]-AveTime[i]);
      float run = (float)AveRun[i];
      float rLow = (float)(AveRun[i]-MinRun[i]); 
      float rHig = (float)(MaxRun[i]-AveRun[i]);
      
      g_c_fit -> SetPoint(i,  date , 1./k);
      g_c_fit -> SetPointError(i, dLow , dHig , eee/k/k, eee/k/k);
      
      g_c_fit_run -> SetPoint(i,  run , 1./k);
      g_c_fit_run -> SetPointError(i, rLow , rHig, eee/k/k, eee/k/k);
      
      h_EoC_chi2 -> Fill(f_EoC[i]->GetChisquare()/f_EoP[i]->GetNDF());
      
      EoC_scale += 1./k;
      EoC_err += eee/k/k;
      ++EoC_nActiveBins;
    }
    else
    {
      std::cout << "Fitting corrected time bin: " << i << "   Fail status: " << fStatus << "   sigma: " << eee << std::endl;
      isValid = false;
    }
    
    if( isValid == true ) validBins.push_back(i);
  }
  
  EoP_scale /= EoP_nActiveBins;
  EoP_err   /= EoP_nActiveBins;
  
  EoC_scale /= EoC_nActiveBins;
  EoC_err   /= EoC_nActiveBins;
  
  
  
  
  
  
  //----------------------------------------
  // Fill the graph for avg laser correction
  
  //fede
  for(unsigned int itr = 0; itr < validBins.size(); ++itr)
  {  
    int i = validBins.at(itr);
    g_las -> SetPoint(itr, (float)AveTime[i], h_Tsp[i]->GetMean() );
    g_LT  -> SetPoint(itr, (float)AveTime[i], AveLT[i] );
    g_LT  -> SetPointError(itr, 0., sqrt(AveLT2[i]-AveLT[i]*AveLT[i]) / sqrt(Entries[i]) );
        
    LCInv_scale += h_Tsp[i]->GetMean();
  }  
  
  LCInv_scale /= validBins.size();
  
  
  
  
  
  
  //---------------
  // Rescale graphs
  
  float yscale = 1.;
  //float yscale = 1./EoC_scale;
  
  for(unsigned int itr = 0; itr < validBins.size(); ++itr)
  {
    double x,y; 
    g_fit -> GetPoint(itr,x,y); 
    g_fit -> SetPoint(itr,x,y*yscale);
    if ( (x > t1) && (x < t2) ) h_EoP_spread -> Fill(y*yscale);
    
    g_c_fit -> GetPoint(itr,x,y); 
    g_c_fit -> SetPoint(itr,x,y*yscale);
    if ( (x > t1) && (x < t2) ) h_EoC_spread -> Fill(y*yscale);
    
    g_fit_run -> GetPoint(itr,x,y); 
    g_fit_run -> SetPoint(itr,x,y*yscale); 
    if ( (x > t1) && (x < t2) ) h_EoP_spread_run -> Fill(y*yscale);
    
    g_c_fit_run -> GetPoint(itr,x,y); 
    g_c_fit_run -> SetPoint(itr,x,y*yscale);
    if ( (x > t1) && (x < t2) ) h_EoC_spread_run -> Fill(y*yscale);
    
    g_las -> GetPoint(itr,x,y);
    g_las -> SetPoint(itr,x,y*yscale*EoP_scale/LCInv_scale);
  }
  
  TF1 EoC_pol0("EoC_pol0","pol0",t1,t2);
  EoC_pol0.SetLineColor(kGreen+2);
  EoC_pol0.SetLineWidth(2);
  EoC_pol0.SetLineStyle(2);
  g_c_fit -> Fit("EoC_pol0","QNR");
  
  
  
  
  
  
  
  
  //----------------------------
  // Print out global quantities
  
  std::cout << std::endl;
  std::cout << "***** Mean scales and errors *****" << std::endl; 
  std::cout << std::fixed;
  std::cout << std::setprecision(4);
  std::cout << "Mean EoP scale: "  << std::setw(6) << EoP_scale   << "   mean EoP error: " << std::setw(8) << EoP_err << std::endl;
  std::cout << "Mean EoC scale: "  << std::setw(6) << EoC_scale   << "   mean EoC error: " << std::setw(8) << EoC_err << std::endl;
  std::cout << "Mean 1/LC scale: " << std::setw(6) << LCInv_scale << std::endl;
  
  
  
  
  
  
  //-----------------
  // Occupancy plots
  //-----------------
  
  TCanvas* c_scOccupancy = new TCanvas("c_scOccupancy","SC occupancy",0,0,1000,500);
  c_scOccupancy -> Divide(2,1);
  
  c_scOccupancy -> cd(1);
  h_scOccupancy_eta -> GetXaxis() -> SetTitle("sc #eta");
  h_scOccupancy_eta -> GetYaxis() -> SetTitle("events");
  h_scOccupancy_eta -> Draw();
  
  c_scOccupancy -> cd(2);
  h_scOccupancy_phi -> GetXaxis() -> SetTitle("sc #phi");
  h_scOccupancy_phi -> GetYaxis() -> SetTitle("events");
  h_scOccupancy_phi -> Draw();
  
  TCanvas* c_seedOccupancy = new TCanvas("c_seedOccupancy","seed occupancy",0,0,1500,500);
  c_seedOccupancy -> Divide(3,1);
  
  c_seedOccupancy -> cd(1);
  h_seedOccupancy_EB -> GetXaxis() -> SetTitle("seed i#eta");
  h_seedOccupancy_EB -> GetYaxis() -> SetTitle("seed i#phi");
  h_seedOccupancy_EB -> Draw("COLZ");
  
  c_seedOccupancy -> cd(2);
  h_seedOccupancy_EEp -> GetXaxis() -> SetTitle("seed ix");
  h_seedOccupancy_EEp -> GetYaxis() -> SetTitle("seed iy");
  h_seedOccupancy_EEp -> Draw("COLZ");
  
  c_seedOccupancy -> cd(3);
  h_seedOccupancy_EEm -> GetXaxis() -> SetTitle("seed ix");
  h_seedOccupancy_EEm -> GetYaxis() -> SetTitle("seed iy");
  h_seedOccupancy_EEm -> Draw("COLZ");
  
  
  
  //-----------
  // Chi2 plots
  //-----------
  
  TCanvas* c_chi2 = new TCanvas("c_chi2","fit chi2",0,0,500,500);
  c_chi2 -> cd();
  
  h_EoC_chi2 -> GetXaxis() -> SetTitle("#chi^{2}/N_{dof}");
  h_EoC_chi2 -> Draw("");
  gPad -> Update();
    
  TPaveStats* s_EoC = new TPaveStats;
  s_EoC = (TPaveStats*)(h_EoC_chi2->GetListOfFunctions()->FindObject("stats"));
  s_EoC -> SetStatFormat("1.4g");
  s_EoC -> SetTextColor(kGreen+2);
  s_EoC->SetY1NDC(0.59);
  s_EoC->SetY2NDC(0.79);
  s_EoC -> Draw("sames");
  gPad -> Update();
  
  h_EoP_chi2 -> GetXaxis() -> SetTitle("#chi^{2}/N_{dof}");
  h_EoP_chi2 -> Draw("sames");
  gPad -> Update();
  
  TPaveStats* s_EoP = new TPaveStats;
  s_EoP = (TPaveStats*)(h_EoP_chi2->GetListOfFunctions()->FindObject("stats"));
  s_EoP -> SetStatFormat("1.4g");
  s_EoP -> SetTextColor(kRed+2);
  s_EoP->SetY1NDC(0.79);
  s_EoP->SetY2NDC(0.99);
  s_EoP -> Draw("sames");
  gPad -> Update();
  
  
  
  
  
  
  //-------------------
  // Final plot vs date
  //-------------------
  
  TCanvas* cplot = new TCanvas("cplot", "history plot vs date",100,100,1000,500);
  cplot->cd();

  TPad *cLeft  = new TPad("pad_0","pad_0",0.00,0.00,0.75,1.00);
  TPad *cRight = new TPad("pad_1","pad_1",0.75,0.00,1.00,1.00);

  cLeft->SetLeftMargin(0.15); 
  cLeft->SetRightMargin(0.025); 
  cRight->SetLeftMargin(0.025); 

  cLeft->Draw();
  cRight->Draw();

  float tYoffset = 1.0; 
  float labSize = 0.05;
  float labSize2 = 0.06;

  cLeft->cd(); 
  
  cLeft->SetGridx();
  cLeft->SetGridy();
  
  TH1F *hPad = (TH1F*)gPad->DrawFrame(t1,0.9,t2,1.05);
  hPad->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00");
  hPad->GetXaxis()->SetTimeDisplay(1);
  hPad->GetXaxis() -> SetRangeUser(MinTime[0]-43200,MaxTime[nBins-1]+43200);
  hPad->GetXaxis()->SetTitle("date (day/month)");
  if( strcmp(EBEE,"EB") == 0 )
    hPad->GetYaxis()->SetTitle("Relative E/p scale"); 
  else
    hPad->GetYaxis()->SetTitle("Relative E/p scale"); 
  hPad->GetYaxis()->SetTitleOffset(tYoffset);
  hPad->GetXaxis()->SetLabelSize(labSize);
  hPad->GetXaxis()->SetTitleSize(labSize2);
  hPad->GetYaxis()->SetLabelSize(labSize);
  hPad->GetYaxis()->SetTitleSize(labSize2);
  hPad -> SetMinimum(yMIN);
  hPad -> SetMaximum(yMAX);
  
  // draw history plot
  g_fit -> SetMarkerStyle(24);
  g_fit -> SetMarkerSize(0.7);
  g_fit -> SetMarkerColor(kRed+2);
  g_fit -> SetLineColor(kRed+2);
  g_fit -> Draw("P");
  g_c_fit -> SetMarkerStyle(20);
  g_c_fit -> SetMarkerColor(kGreen+2);
  g_c_fit -> SetLineColor(kGreen+2);
  g_c_fit -> SetMarkerSize(0.7);
  g_c_fit -> Draw("P,same");
  g_las -> SetLineColor(kAzure-2);
  g_las -> SetLineWidth(2);
  g_las -> Draw("L,same");
  
  TLegend* legend = new TLegend(0.60,0.78,0.90,0.94);
  legend -> SetLineColor(kWhite);
  legend -> SetLineWidth(0);
  legend -> SetFillColor(kWhite);
  legend -> SetFillStyle(0);
  legend -> SetTextFont(42);
  legend -> SetTextSize(0.04);
  legend -> AddEntry(g_c_fit,"with LM correction","PL");
  legend -> AddEntry(g_fit,  "without LM correction","PL");
  legend -> AddEntry(g_las,  "1 / LM correction","L");
  legend -> Draw("same");
  
  char latexBuffer[250];
  
  sprintf(latexBuffer,"CMS 2012 Preliminary");
  TLatex* latex = new TLatex(0.18,0.89,latexBuffer);  
  latex -> SetNDC();
  latex -> SetTextFont(62);
  latex -> SetTextSize(0.05);
  latex -> Draw("same");
  
  //sprintf(latexBuffer,"#sqrt{s} = 8 TeV   L = 3.95 fb^{-1}");
  sprintf(latexBuffer,"#sqrt{s} = 8 TeV");
  TLatex* latex2 = new TLatex(0.18,0.84,latexBuffer);  
  latex2 -> SetNDC();
  latex2 -> SetTextFont(42);
  latex2 -> SetTextSize(0.05);
  latex2 -> Draw("same");
  
  if( strcmp(EBEE,"EB") == 0 )
    sprintf(latexBuffer,"ECAL Barrel");
  else
    sprintf(latexBuffer,"ECAL Endcap");
  TLatex* latex3 = new TLatex(0.18,0.19,latexBuffer);
  latex3 -> SetNDC();
  latex3 -> SetTextFont(42);
  latex3 -> SetTextSize(0.05);
  latex3 -> Draw("same");
  
  //sprintf(latexBuffer,"%.2E events",1.*nSavePts);
  //TLatex* latex4 = new TLatex(0.18,0.24,latexBuffer);  
  //latex4 -> SetNDC();
  //latex4 -> SetTextFont(42);
  //latex4 -> SetTextSize(0.04);
  //latex4 -> Draw("same");
  //
  //sprintf(latexBuffer,"%d events/bin - %d bins",evtsPerPoint,nBins);
  //TLatex* latex5 = new TLatex(0.18,0.19,latexBuffer);  
  //latex5 -> SetNDC();
  //latex5 -> SetTextFont(42);
  //latex5 -> SetTextSize(0.04);
  //latex5 -> Draw("same");
  
  
  cRight -> cd();
  
  TPaveStats* s_EoP_spread = new TPaveStats();
  TPaveStats* s_EoC_spread = new TPaveStats();
  
  
  h_EoC_spread -> SetFillStyle(3001);
  h_EoC_spread -> SetFillColor(kGreen+2);
  h_EoC_spread->GetYaxis()->SetLabelSize(0.09);
  h_EoC_spread->GetYaxis()->SetLabelOffset(-0.03);
  h_EoC_spread->GetYaxis()->SetTitleSize(0.08);
  h_EoC_spread->GetYaxis()->SetNdivisions(505);
  h_EoC_spread->GetXaxis()->SetLabelOffset(1000);
  
  h_EoC_spread -> Draw("hbar");
  gPad -> Update();
  
  s_EoC_spread = (TPaveStats*)(h_EoC_spread->GetListOfFunctions()->FindObject("stats"));
  s_EoC_spread -> SetStatFormat("1.4g");
  s_EoC_spread->SetX1NDC(0.06); //new x start position
  s_EoC_spread->SetX2NDC(0.71); //new x end position
  s_EoC_spread->SetY1NDC(0.93); //new x start position
  s_EoC_spread->SetY2NDC(0.84); //new x end position
  s_EoC_spread -> SetOptStat(1100);
  s_EoC_spread ->SetTextColor(kGreen+2);
  s_EoC_spread ->SetTextSize(0.08);
  s_EoC_spread -> Draw("sames");
  
  
  h_EoP_spread -> SetFillStyle(3001);
  h_EoP_spread -> SetFillColor(kRed+2);
  h_EoP_spread -> Draw("hbarsames");
  gPad -> Update();
  s_EoP_spread = (TPaveStats*)(h_EoP_spread->GetListOfFunctions()->FindObject("stats"));
  s_EoP_spread -> SetStatFormat("1.4g");
  s_EoP_spread->SetX1NDC(0.06); //new x start position
  s_EoP_spread->SetX2NDC(0.71); //new x end position
  s_EoP_spread->SetY1NDC(0.83); //new x start position
  s_EoP_spread->SetY2NDC(0.74); //new x end position
  s_EoP_spread ->SetOptStat(1100);
  s_EoP_spread ->SetTextColor(kRed+2);
  s_EoP_spread ->SetTextSize(0.08);
  s_EoP_spread -> Draw("sames");
  
  /*
  h_EoP_spread -> SetFillStyle(3001);
  h_EoP_spread -> SetFillColor(kRed+2);
  h_EoP_spread -> Draw("hbarsame");
  gPad -> Update();
  */
  
  
  
  //------------------
  // Final plot vs run
  //------------------
  
  TCanvas* cplot_run = new TCanvas("cplot_run", "history plot vs run",100,100,1000,500);
  cplot_run->cd();
  
  cLeft  = new TPad("pad_0_run","pad_0_run",0.00,0.00,0.75,1.00);
  cRight = new TPad("pad_1_run","pad_1_run",0.75,0.00,1.00,1.00);

  cLeft->SetLeftMargin(0.15); 
  cLeft->SetRightMargin(0.025); 
  cRight->SetLeftMargin(0.025); 

  cLeft->Draw();
  cRight->Draw();

  tYoffset = 1.5; 
  labSize = 0.04;
  labSize2 = 0.07;

  cLeft->cd(); 

  cLeft->SetGridx();
  cLeft->SetGridy();
  
  hPad = (TH1F*)gPad->DrawFrame(MinRun[0]-1000,0.9,MaxRun[nBins-1]+1000,1.05);
  hPad->GetXaxis()->SetTitle("run");
  if( strcmp(EBEE,"EB") == 0 )
    hPad->GetYaxis()->SetTitle("Relative E/p scale"); 
  else
    hPad->GetYaxis()->SetTitle("Relative E/p scale"); 
  hPad->GetYaxis()->SetTitleOffset(tYoffset);
  hPad->GetXaxis()->SetLabelSize(labSize);
  hPad->GetXaxis()->SetTitleSize(labSize);
  hPad->GetYaxis()->SetLabelSize(labSize);
  hPad->GetYaxis()->SetTitleSize(labSize);
  hPad -> SetMinimum(yMIN);
  hPad -> SetMaximum(yMAX);
  
  // draw history plot
  g_fit_run -> SetMarkerStyle(20);
  g_fit_run -> SetMarkerSize(0.7);
  g_fit_run -> SetMarkerColor(kRed+2);
  g_fit_run -> SetLineColor(kRed+2);
  g_fit_run -> Draw("P");
  g_c_fit_run -> SetMarkerStyle(20);
  g_c_fit_run -> SetMarkerColor(kGreen+2);
  g_c_fit_run -> SetLineColor(kGreen+2);
  g_c_fit_run -> SetMarkerSize(0.7);
  g_c_fit_run -> Draw("P,same");
  
  
  cRight -> cd();
  
  s_EoP_spread = new TPaveStats();
  s_EoC_spread = new TPaveStats();
  
  
  h_EoC_spread_run -> SetFillStyle(3001);
  h_EoC_spread_run -> SetFillColor(kGreen+2);
  h_EoC_spread_run->GetYaxis()->SetLabelSize(labSize2);
  h_EoC_spread_run->GetYaxis()->SetTitleSize(labSize2);
  h_EoC_spread_run->GetYaxis()->SetNdivisions(505);
  h_EoC_spread_run->GetYaxis()->SetLabelOffset(-0.02);
  h_EoC_spread_run->GetXaxis()->SetLabelOffset(1000);

  h_EoC_spread_run -> Draw("hbar");
  gPad -> Update();
  
  s_EoC_spread = (TPaveStats*)(h_EoC_spread_run->GetListOfFunctions()->FindObject("stats"));
  s_EoC_spread ->SetTextColor(kGreen+2);
  s_EoC_spread ->SetTextSize(0.06);
  s_EoC_spread->SetX1NDC(0.49); //new x start position
  s_EoC_spread->SetX2NDC(0.99); //new x end position
  s_EoC_spread->SetY1NDC(0.875); //new x start position
  s_EoC_spread->SetY2NDC(0.990); //new x end position
  s_EoC_spread -> SetOptStat(1100);
  s_EoC_spread -> Draw("sames");

  h_EoP_spread_run -> SetFillStyle(3001);
  h_EoP_spread_run -> SetFillColor(kRed+2);
  h_EoP_spread_run -> Draw("hbarsames");
  gPad -> Update();
  
  s_EoP_spread = (TPaveStats*)(h_EoP_spread_run->GetListOfFunctions()->FindObject("stats"));
  s_EoP_spread->SetX1NDC(0.49); //new x start position
  s_EoP_spread->SetX2NDC(0.99); //new x end position
  s_EoP_spread->SetY1NDC(0.750); //new x start position
  s_EoP_spread->SetY2NDC(0.875); //new x end position
  s_EoP_spread ->SetOptStat(1100);
  s_EoP_spread ->SetTextColor(kRed+2);
  s_EoP_spread ->SetTextSize(0.06);
  s_EoP_spread -> Draw("sames");
  
  
  
  
  
  
  c_chi2 -> Print((folderName+"/"+folderName+"_fitChi2.png").c_str(),"png");
  c_scOccupancy -> Print((folderName+"/"+folderName+"_scOccupancy.png").c_str(),"png");
  c_seedOccupancy -> Print((folderName+"/"+folderName+"_seedOccupancy.png").c_str(),"png");
  cplot -> Print((folderName+"/"+folderName+"_history_vsTime.png").c_str(),"png");
  cplot_run -> Print((folderName+"/"+folderName+"_history_vsRun.png").c_str(),"png");
  
  c_chi2 -> Print((folderName+"/"+folderName+"_fitChi2.pdf").c_str(),"pdf");
  c_scOccupancy -> Print((folderName+"/"+folderName+"_scOccupancy.pdf").c_str(),"pdf");
  c_seedOccupancy -> Print((folderName+"/"+folderName+"_seedOccupancy.pdf").c_str(),"pdf");
  cplot -> Print((folderName+"/"+folderName+"_history_vsTime.pdf").c_str(),"pdf");
  cplot_run -> Print((folderName+"/"+folderName+"_history_vsRun.pdf").c_str(),"pdf");
  
  cplot -> SaveAs((folderName+"/"+folderName+"_history_vsTime.C").c_str());
  cplot_run -> SaveAs((folderName+"/"+folderName+"_history_vsRun.C").c_str());
  
  
  
   o -> cd();
  
   h_template -> Write();

   h_scOccupancy_eta   -> Write();
   h_scOccupancy_phi   -> Write();
   h_seedOccupancy_EB  -> Write(); 
   h_seedOccupancy_EEp -> Write();
   h_seedOccupancy_EEm -> Write();

   g_fit   -> Write("g_fit");
   g_c_fit -> Write("g_c_fit");
   g_fit_run   -> Write("g_fit_run");
   g_c_fit_run -> Write("g_c_fit_run");
   g_las -> Write("g_las");
   g_LT -> Write("g_LT");
   
   h_EoP_chi2 -> Write();
   h_EoC_chi2 -> Write();
  
   //for(int i = 0; i < nBins; ++i)
   //{
   //  h_EoP[i] -> GetXaxis() -> SetTitle("E/p");
   //  h_EoP[i] -> Write();
   //
   //  h_EoC[i] -> GetXaxis() -> SetTitle("E/p");
   //  h_EoC[i] -> Write();
   //
   //  h_Tsp[i] -> Write();
   //
   //  h_Cvl[i] -> Write();
   //}

  o -> Close();
}
Esempio n. 12
0
int main(int argc, char** argv)
{
  //Check if all nedeed arguments to parse are there                                                                                                                               
  if(argc != 2)
  {
    std::cerr << ">>>>> SimpleNtplePreselection::usage: " << argv[0] << " configFileName" << std::endl ;
    return 1;
  }
  
  
  
  // Parse the config file                                                                                                                                                          
  parseConfigFile (argv[1]) ;
  
  std::string inputFileList = gConfigParser -> readStringOption("Input::inputFileList");
  std::string jsonFileName  = gConfigParser -> readStringOption("Input::jsonFileName");  
    
  std::string outputRootFilePath = gConfigParser -> readStringOption("Output::outputRootFilePath");
  std::string outputRootFileName = gConfigParser -> readStringOption("Output::outputRootFileName");  
  
  int entryMAX    = gConfigParser -> readIntOption("Options::entryMAX");
  int entryMODULO = gConfigParser -> readIntOption("Options::entryMODULO");
  int dataFlag    = gConfigParser -> readIntOption("Options::dataFlag");
  
  int nEleMIN = gConfigParser -> readIntOption  ("Cuts::nEleMIN");
  
  float scEtMIN = gConfigParser -> readFloatOption("Cuts::scEtMIN");
  
  float eleCombIsoOverPtEBMAX = gConfigParser -> readFloatOption("Cuts::eleCombIsoOverPtEBMAX");
  float eleTkIsoOverPtEBMAX   = gConfigParser -> readFloatOption("Cuts::eleTkIsoOverPtEBMAX");
  float eleEmIsoOverPtEBMAX   = gConfigParser -> readFloatOption("Cuts::eleEmIsoOverPtEBMAX");
  float eleHadIsoOverPtEBMAX  = gConfigParser -> readFloatOption("Cuts::eleHadIsoOverPtEBMAX");
  float eleSigmaIetaIetaEBMAX = gConfigParser -> readFloatOption("Cuts::eleSigmaIetaIetaEBMAX");
  float eleDphiInEBMAX        = gConfigParser -> readFloatOption("Cuts::eleDphiInEBMAX");
  float eleDetaInEBMAX        = gConfigParser -> readFloatOption("Cuts::eleDetaInEBMAX");
  float eleHOverEEBMAX        = gConfigParser -> readFloatOption("Cuts::eleHOverEEBMAX");
  
  float eleCombIsoOverPtEEMAX = gConfigParser -> readFloatOption("Cuts::eleCombIsoOverPtEEMAX");
  float eleTkIsoOverPtEEMAX   = gConfigParser -> readFloatOption("Cuts::eleTkIsoOverPtEEMAX");
  float eleEmIsoOverPtEEMAX   = gConfigParser -> readFloatOption("Cuts::eleEmIsoOverPtEEMAX");
  float eleHadIsoOverPtEEMAX  = gConfigParser -> readFloatOption("Cuts::eleHadIsoOverPtEEMAX");
  float eleSigmaIetaIetaEEMAX = gConfigParser -> readFloatOption("Cuts::eleSigmaIetaIetaEEMAX");  
  float eleDphiInEEMAX        = gConfigParser -> readFloatOption("Cuts::eleDphiInEEMAX");
  float eleDetaInEEMAX        = gConfigParser -> readFloatOption("Cuts::eleDetaInEEMAX");
  float eleHOverEEEMAX        = gConfigParser -> readFloatOption("Cuts::eleHOverEEEMAX");
  
  float metEtMIN = gConfigParser -> readFloatOption("Cuts::metEtMIN");
  
  
  
  
  
  
  // Get number of events
  std::cout << ">>> SimpleNtplePreselection::Get number of events" << std::endl;
  std::map<int,int> totalEvents = GetTotalEvents("AllPassFilterBegin/totalEvents", inputFileList.c_str());  
  
  std::string L1FilterName = "AllPassFilterL1Filter/totalEvents"; 
  std::map<int,int> L1FilterEvents = GetTotalEvents(L1FilterName.c_str(), inputFileList.c_str());  
  
  std::string GoodVertexFilterName = "AllPassFilterGoodVertexFilter/totalEvents"; 
  std::map<int,int> GoodVertexFilterEvents = GetTotalEvents(GoodVertexFilterName.c_str(), inputFileList.c_str());  
  
  std::string NoScrapingFilterName = "AllPassFilterNoScrapingFilter/totalEvents"; 
  std::map<int,int> NoScrapingFilterEvents = GetTotalEvents(NoScrapingFilterName.c_str(), inputFileList.c_str());  
  
  std::string ElectronFilterName = "AllPassFilterElectronFilter/totalEvents"; 
  std::map<int,int> ElectronFilterEvents = GetTotalEvents(ElectronFilterName.c_str(), inputFileList.c_str());  
  
  
  
  
  
  
  // Get run/LS map from JSON file
  std::cout << ">>> SimpleNtplePreselection::Get run/LS map from JSON file " << jsonFileName << std::endl;
  std::map<int, std::vector<std::pair<int, int> > > jsonMap;
  if(dataFlag == 1) jsonMap = readJSONFile(jsonFileName);
  
  
  
  
  
  
  // Open old tree
  std::cout << ">>> SimpleNtplePreselection::Open old tree" << std::endl;
  std::string treeName = "simpleNtple/SimpleNtple";
  TChain* chain = new TChain(treeName.c_str());
  if(!FillChain(*chain, inputFileList.c_str())) return 1;
  treeReader reader((TTree*)(chain), false);
  
  
  
  // Open output root file for clone tree
  TFile outputRootFile((outputRootFilePath+outputRootFileName).c_str(), "RECREATE");
  outputRootFile.cd();
  
  TTree* cloneTree = chain -> CloneTree(0);
  
  
  
  // define histograms
  std::cout << ">>> SimpleNtplePreselection::Define histograms" << std::endl;
  int nStep = 9;
  TH1F* events = new TH1F("events", "events", nStep, 0., 1.*nStep);
  std::map<int, int> stepEvents;
  std::map<int, std::string> stepName;

  int step = 1;
  stepEvents[step] = totalEvents[1];
  stepName[step] = "total events";

  step = 2;
  stepEvents[step] = L1FilterEvents[1];
  stepName[step] = "L1Filter";
  
  step = 3;
  stepEvents[step] = GoodVertexFilterEvents[1];
  stepName[step] = "GoodVertexFilter";
  
  step = 4;
  stepEvents[step] = NoScrapingFilterEvents[1];
  stepName[step] = "NoScrapingFilter";
  
  step = 5;
  stepEvents[step] = ElectronFilterEvents[1];
  stepName[step] = "ElectronFilter";
  
  
  
  
  
  
  // Loop over events
  std::cout << ">>>>> SimpleNtplePreselection::Read " << chain -> GetEntries() << " entries" << std::endl;  
  for(int entry = 0 ; entry < chain -> GetEntries() ; ++entry)
  {
    reader.GetEntry(entry);
    if((entry%entryMODULO) == 0) std::cout << ">>>>> SimpleNtplePreselection::GetEntry " << entry << std::endl;   
    if(entry == entryMAX) break;
    
    
    
    //***********************
    // STEP 6 - HLT selection
    step = 6;
    //std::cout << ">>> step: " << step << std::endl;
    stepName[step] = "HLT";
    
    bool skipEvent = true;
    
    std::vector<std::string> HLT_names = *(reader.GetString("HLT_Names"));
    for(unsigned int HLTIt = 0; HLTIt < HLT_names.size(); ++HLTIt)
    {
      if( (reader.GetString("HLT_Names")->at(HLTIt) == "HLT_Photon15_L1R") &&
	  (reader.GetFloat("HLT_Accept")->at(HLTIt) == 1) )
        skipEvent = false;
      
      if( (reader.GetString("HLT_Names")->at(HLTIt) == "HLT_Ele15_LW_L1R") &&
          (reader.GetFloat("HLT_Accept")->at(HLTIt) == 1) )
        skipEvent = false;
      
      if( (reader.GetString("HLT_Names")->at(HLTIt) == "HLT_Ele15_SW_L1R") &&
           (reader.GetFloat("HLT_Accept")->at(HLTIt) == 1) )
        skipEvent = false;
      
      if( (reader.GetString("HLT_Names")->at(HLTIt) == "HLT_Ele15_SW_CaloEleId_L1R") &&
          (reader.GetFloat("HLT_Accept")->at(HLTIt) == 1) )
        skipEvent = false;
    }
    
    
    if( skipEvent == true ) continue;
    stepEvents[step] += 1;    
    
    
    
    
    
    
    //**************************
    // STEP 7 - run/LS selection
    step = step+1;
    //std::cout << ">>> step: " << step << std::endl;
    stepName[step] = "run/LS";    
    
    skipEvent = false;
    if(dataFlag == 1)
    {
      int runId  = reader.GetInt("runId")->at(0);
      int lumiId = reader.GetInt("lumiId")->at(0);
      if(AcceptEventByRunAndLumiSection(runId, lumiId, jsonMap) == false) skipEvent = true;      
    }
    
    if( skipEvent == true ) continue;
    stepEvents[step] += 1;
    
    
    
    
    
    
    //*************************
    // STEP 8 - cut on electron
    step = step+1;
    //std::cout << ">>> step: " << step << std::endl;
    stepName[step] = "electron selection";
    
    int nEle = 0;
    for(unsigned int eleIt = 0; eleIt < (reader.Get4V("electrons")->size()); ++eleIt)
    {
      // SC Et
      if( reader.GetFloat("electrons_scEt")->at(eleIt) < scEtMIN ) continue;
      
      
      
      // isolation + eleId
      float pt = reader.Get4V("electrons")->at(eleIt).pt();
      
      float tkIso  = reader.GetFloat("electrons_tkIso03")->at(eleIt);
      float emIso  = reader.GetFloat("electrons_emIso03")->at(eleIt);
      float hadIso = reader.GetFloat("electrons_hadIso03_1")->at(eleIt) +
                     reader.GetFloat("electrons_hadIso03_2")->at(eleIt);
      
      float sigmaIetaIeta = reader.GetFloat("electrons_sigmaIetaIeta")->at(eleIt);
      float dPhiIn        = reader.GetFloat("electrons_deltaPhiIn")->at(eleIt);
      float dEtaIn        = reader.GetFloat("electrons_deltaEtaIn")->at(eleIt);
      float hOverE        = reader.GetFloat("electrons_hOverE")->at(eleIt);
      
      if( (reader.GetInt("electrons_isEB")->at(eleIt)) == 1 )
      {      
        if( ((tkIso + std::max(0., emIso-1.) + hadIso) / pt) > eleCombIsoOverPtEBMAX ) continue;
        
        if( (tkIso  / pt) > eleTkIsoOverPtEBMAX ) continue;
        if( (emIso  / pt) > eleEmIsoOverPtEBMAX ) continue;
        if( (hadIso / pt) > eleHadIsoOverPtEBMAX ) continue;
        
        if( sigmaIetaIeta > eleSigmaIetaIetaEBMAX ) continue;
        if(  fabs(dPhiIn) > eleDphiInEBMAX ) continue;
        if(  fabs(dEtaIn) > eleDetaInEBMAX ) continue;
        if(        hOverE > eleHOverEEBMAX ) continue;
      }
      
      else
      {      
        if( ((tkIso + emIso + hadIso) / pt) > eleCombIsoOverPtEEMAX ) continue;
        
        if( (tkIso  / pt) > eleTkIsoOverPtEEMAX ) continue;
        if( (emIso  / pt) > eleEmIsoOverPtEEMAX ) continue;
        if( (hadIso / pt) > eleHadIsoOverPtEEMAX ) continue;
        
        if( sigmaIetaIeta > eleSigmaIetaIetaEEMAX ) continue;
        if(  fabs(dPhiIn) > eleDphiInEEMAX ) continue;
        if(  fabs(dEtaIn) > eleDetaInEEMAX ) continue;
        if(        hOverE > eleHOverEEEMAX ) continue;
      }
      
      
      
      // conversion rejection
      if( reader.GetInt("electrons_mishits")->at(eleIt) > 0 ) continue;
      if( reader.GetInt("electrons_nAmbiguousGsfTracks")->at(eleIt) > 0 ) continue;
      if( ( fabs(reader.GetFloat("electrons_dist")->at(eleIt)) < 0.02 ) &&
          ( fabs(reader.GetFloat("electrons_dcot")->at(eleIt)) < 0.02 ) ) continue;
      
      
      
      // spike removal
      if( reader.GetInt("electrons_seedSeverityLevel")->at(eleIt) != 0 ) continue;
      if( reader.GetInt("electrons_seedFlag")->at(eleIt) != 0 ) continue;
      
      
      
      ++nEle;
    }
    
    if( nEle < nEleMIN ) continue;
    stepEvents[step] += 1;
    
    
    
    
    
    
    //********************
    // STEP 9 - cut on met
    step = step+1;
    //std::cout << ">>> step: " << step << std::endl;
    stepName[step] = "met selection";
    
    if( (reader.Get4V("PFMet")->at(0)).Et() < metEtMIN ) continue;
    
    stepEvents[step] += 1;
    
    
    
    
    
    
    //***********
    // CLONE TREE
    
    cloneTree -> Fill();
    
  } // loop over the events
  
  
  
  
  
  
  // save histograms
  for(step = 1; step <= nStep; ++step)
  {
    events -> SetBinContent(step, stepEvents[step]);
    events -> GetXaxis() -> SetBinLabel(step, stepName[step].c_str());
  }
  
  events -> Write();
  
  cloneTree -> AutoSave();
  outputRootFile.Close();
  
  
  
  return 0;
}
int main (int argc, char ** argv) 
{
    
  ///Check if all nedeed arguments to parse are there
  if(argc != 2)
  {
    std::cerr << ">>>>> FastCalibrator::usage: " << argv[0] << " configFileName" << std::endl ;
    return 1;
  }
    
  /// Parse the config file
  parseConfigFile (argv[1]) ;
 
//   std::string inputFile       = gConfigParser -> readStringOption("Input::inputFile");
  std::string inputList       = gConfigParser -> readStringOption("Input::inputList");

  std::string inputTree       = gConfigParser -> readStringOption("Input::inputTree");

  std::string inputFileDeadXtal ="NULL" ;
  try {
        inputFileDeadXtal = gConfigParser -> readStringOption("Input::inputFileDeadXtal");
   }
   catch ( char const* exceptionString ){
   std::cerr << " exception = " << exceptionString << std::endl;

   }
  bool isMiscalib = gConfigParser -> readBoolOption("Input::isMiscalib");
  bool isSaveEPDistribution = gConfigParser -> readBoolOption("Input::isSaveEPDistribution");
  bool isEPselection = gConfigParser -> readBoolOption("Input::isEPselection");
  bool isR9selection = gConfigParser -> readBoolOption("Input::isR9selection");
  bool isMCTruth = gConfigParser -> readBoolOption("Input::isMCTruth");

  std::string outputFile      = gConfigParser -> readStringOption("Output::outputFile");

 
  
  int numberOfEvents       = gConfigParser -> readIntOption("Options::numberOfEvents");
  int useZ                 = gConfigParser -> readIntOption("Options::useZ");
  int useW                 = gConfigParser -> readIntOption("Options::useW");
  int splitStat            = gConfigParser -> readIntOption("Options::splitStat");
  int nLoops               = gConfigParser -> readIntOption("Options::nLoops");
  
  /// open ntupla of data or MC
  TChain * albero = new TChain (inputTree.c_str());
  FillChain(*albero,inputList); 
  
  ///Use the whole sample statistics if numberOfEvents < 0
  if ( numberOfEvents < 0 ) numberOfEvents = albero->GetEntries(); 
  

  /// run in normal mode: full statistics
  if ( splitStat == 0 ) {
   
    TString name ;
    TString name_tmp;
    if(isMiscalib == true && useZ == 1 && isR9selection ==true ) name_tmp = Form ("%s_Z_R9_miscalib",outputFile.c_str());
    if(isMiscalib == true && useZ == 1 && isEPselection ==true ) name_tmp = Form ("%s_Z_EP_miscalib",outputFile.c_str());
    if(isMiscalib == true && useZ == 1 && isEPselection ==false && isR9selection==false ) name_tmp =Form ("%s_Z_noEP_miscalib",outputFile.c_str());
    
    if(isMiscalib == false && useZ == 1 && isR9selection ==true ) name_tmp = Form ("%s_Z_R9",outputFile.c_str());
    if(isMiscalib == false && useZ == 1 && isEPselection ==true ) name_tmp = Form ("%s_Z_EP",outputFile.c_str());
    if(isMiscalib == false && useZ == 1 && isEPselection ==false && isR9selection==false ) name_tmp =Form ("%s_Z_noEP",outputFile.c_str());
    

    if(isMiscalib == true && useZ == 0 && isR9selection ==true ) name_tmp = Form ("%s_R9_miscalib",outputFile.c_str());
    if(isMiscalib == true && useZ == 0 && isEPselection ==true ) name_tmp = Form ("%s_EP_miscalib",outputFile.c_str());
    if(isMiscalib == true && useZ == 0 && isEPselection ==false && isR9selection==false ) name_tmp =Form ("%s_noEP_miscalib",outputFile.c_str());
    
    
    if(isMiscalib == false && useZ == 0 && isR9selection ==true ) name_tmp = Form ("%s_R9",outputFile.c_str());
    if(isMiscalib == false && useZ == 0 && isEPselection ==true ) name_tmp = Form ("%s_EP",outputFile.c_str());
    if(isMiscalib == false && useZ == 0 && isEPselection ==false && isR9selection==false ) name_tmp =Form ("%s_noEP",outputFile.c_str());
         
    name = Form("%s.root",name_tmp.Data());
    TFile *f1 = new TFile(name,"RECREATE");

    TString outEPDistribution = "Weight_"+name;
    
    TString DeadXtal = Form("%s",inputFileDeadXtal.c_str());    

    if(isSaveEPDistribution == true)
    {
     FastCalibratorEB_MVA analyzer(albero,outEPDistribution);
     analyzer.bookHistos(nLoops);
     analyzer.AcquireDeadXtal(DeadXtal);
     analyzer.Loop(numberOfEvents, useZ, useW, splitStat, nLoops, isMiscalib,isSaveEPDistribution,isEPselection,isR9selection,isMCTruth);
     analyzer.saveHistos(f1);
    }
    else
    {
     FastCalibratorEB_MVA analyzer(albero);
     analyzer.bookHistos(nLoops);
     analyzer.AcquireDeadXtal(DeadXtal);
     analyzer.Loop(numberOfEvents, useZ, useW, splitStat, nLoops, isMiscalib,isSaveEPDistribution,isEPselection,isR9selection,isMCTruth);
     analyzer.saveHistos(f1);
    }
   
  }

  /// run in even-odd mode: half statistics
  else if ( splitStat == 1 ) {
    
    /// Prepare the outputs
    std::string evenFile = "Even_" + outputFile;
    std::string oddFile = "Odd_" + outputFile;
    TString name;
    TString name2;
    
    if(isMiscalib == true && useZ == 1 && isR9selection==true)
    { name = Form ("%s_Z_R9_miscalib.root",evenFile.c_str());
      name2 = Form ("%s_Z_R9_miscalib.root",oddFile.c_str());
    }
    
    if(isMiscalib == true && useZ == 1 && isEPselection==true)
    { name = Form ("%s_Z_EP_miscalib.root",evenFile.c_str());
      name2 = Form ("%s_Z_EP_miscalib.root",oddFile.c_str());
    }
    if(isMiscalib == true && useZ == 1 && isR9selection==false && isEPselection==false)
    { name = Form ("%s_Z_noEP_miscalib.root",evenFile.c_str());
      name2 = Form ("%s_Z_noEP_miscalib.root",oddFile.c_str());
    }



    if(isMiscalib == false && useZ == 1 && isR9selection==true)
    { name = Form ("%s_Z_R9.root",evenFile.c_str());
      name2 = Form ("%s_Z_R9.root",oddFile.c_str());
    }
    
    if(isMiscalib == false && useZ == 1 && isEPselection==true)
    { name = Form ("%s_Z_EP.root",evenFile.c_str());
      name2 = Form ("%s_Z_EP.root",oddFile.c_str());
    }
    if(isMiscalib == false && useZ == 1 && isR9selection==false && isEPselection==false)
    { name = Form ("%s_Z_noEP.root",evenFile.c_str());
      name2 = Form ("%s_Z_noEP.root",oddFile.c_str());
    }
    

    if(isMiscalib == true && useZ == 0 && isR9selection==true)
    { name = Form ("%s_R9_miscalib.root",evenFile.c_str());
      name2 = Form ("%s_R9_miscalib.root",oddFile.c_str());
    }
    
    if(isMiscalib == true && useZ == 0 && isEPselection==true)
    { name = Form ("%s_EP_miscalib.root",evenFile.c_str());
      name2 = Form ("%s_EP_miscalib.root",oddFile.c_str());
    }
    if(isMiscalib == true && useZ == 0 && isR9selection==false && isEPselection==false)
    { name = Form ("%s_noEP_miscalib.root",evenFile.c_str());
      name2 = Form ("%s_noEP_miscalib.root",oddFile.c_str());
    }

    
    if(isMiscalib == false && useZ == 0 && isR9selection==true)
    { name = Form ("%s_R9.root",evenFile.c_str());
      name2 = Form ("%s_R9.root",oddFile.c_str());
    }
    
    if(isMiscalib == false && useZ == 0 && isEPselection==true)
    { name = Form ("%s_EP.root",evenFile.c_str());
      name2 = Form ("%s_EP.root",oddFile.c_str());
    }
    if(isMiscalib == false && useZ == 0 && isR9selection==false && isEPselection==false)
    { name = Form ("%s_noEP.root",evenFile.c_str());
      name2 = Form ("%s_noEP.root",oddFile.c_str());
    }

    TFile *f1 = new TFile(name,"RECREATE");
    TFile *f2 = new TFile(name2,"RECREATE");

    TString DeadXtal = Form("%s",inputFileDeadXtal.c_str());
     
    /// Run on odd
    FastCalibratorEB_MVA analyzer_even(albero);
    analyzer_even.bookHistos(nLoops);
    analyzer_even.AcquireDeadXtal(DeadXtal);
    analyzer_even.Loop(numberOfEvents, useZ, useW, splitStat, nLoops,isMiscalib,isSaveEPDistribution,isEPselection,isR9selection,isMCTruth);
    analyzer_even.saveHistos(f1);
  
    /// Run on even
    FastCalibratorEB_MVA analyzer_odd(albero);
    analyzer_odd.bookHistos(nLoops);
    analyzer_odd.AcquireDeadXtal(DeadXtal);
    analyzer_odd.Loop(numberOfEvents, useZ, useW, splitStat*(-1), nLoops,isMiscalib,isSaveEPDistribution,isEPselection,isR9selection,isMCTruth);
    analyzer_odd.saveHistos(f2);
    
  }

  delete albero;
  return 0;
}
Esempio n. 14
0
int main(int argc, char** argv)
{
 //Check if all nedeed arguments to parse are there                                                                                                                               
 if(argc != 2)
 {
  std::cerr << ">>>>> analysis.cpp::usage: " << argv[0] << " configFileName" << std::endl ;
  return 1;
 }
 
 // Parse the config file                                                                                                                                                          
 parseConfigFile (argv[1]) ;
 
 std::string treeName      = gConfigParser -> readStringOption("Input::treeName");
 std::string inputFileList = gConfigParser -> readStringOption("Input::inputFileList");
 
 int entryMAX = gConfigParser -> readIntOption("Input::entryMAX");
 int entryMIN = gConfigParser -> readIntOption("Input::entryMIN");
 int entryMOD = gConfigParser -> readIntOption("Input::entryMOD");
 
 
 std::cout << ">>>>> input::entryMAX  " << entryMAX  << std::endl;  
 std::cout << ">>>>> input::entryMOD  " << entryMOD  << std::endl;  

 std::string outputFileName    = gConfigParser -> readStringOption("Output::fileName");
 std::cout << ">>>>> output::fileName  " << outputFileName  << std::endl;  
 
 
 // Open ntple
 TChain* chain = new TChain(treeName.c_str());
 if(!FillChain(*chain, inputFileList.c_str())) return 1;
 treeReader reader((TTree*)(chain));
 

 double MassW =  gConfigParser -> readDoubleOption("Input::MassW");
 
 double dPt =  gConfigParser  -> readDoubleOption("Input::dPt");
 double dEta =  gConfigParser -> readDoubleOption("Input::dEta"); 

 double minPt =  gConfigParser  -> readDoubleOption("Input::minPt");
 double maxPt =  gConfigParser  -> readDoubleOption("Input::maxPt");
 double maxEta =  gConfigParser -> readDoubleOption("Input::maxEta");
 
 
 std::cout << ">>>>> data::MassW  " << MassW  << std::endl;  
 std::cout << ">>>>> data::dPt    " << dPt    << std::endl;  
 std::cout << ">>>>> data::dEta   " << dEta   << std::endl;  
 std::cout << ">>>>> data::minPt  " << minPt  << std::endl;  
 std::cout << ">>>>> data::maxPt  " << maxPt  << std::endl;  
 std::cout << ">>>>> data::maxEta " << maxEta << std::endl;  
 std::cout << ">>>>> data::MassW  " << MassW  << std::endl;  
 
 
 ///==============================================================
 JetCalibrator myJetCalibrator(MassW,minPt,maxPt,maxEta,dPt,dEta);
 ///==============================================================
 
 std::cout << ">>>>> JetCalibrator::PtMin      " << myJetCalibrator.getPtMin()      << std::endl;  
 std::cout << ">>>>> JetCalibrator::PtMax      " << myJetCalibrator.getPtMax()      << std::endl;  
 std::cout << ">>>>> JetCalibrator::EtaMax     " << myJetCalibrator.getEtaMax()     << std::endl;  
 std::cout << ">>>>> JetCalibrator::DPt        " << myJetCalibrator.getDPt()        << std::endl;  
 std::cout << ">>>>> JetCalibrator::DEta       " << myJetCalibrator.getDEta()       << std::endl;  
 std::cout << ">>>>> JetCalibrator::IntPt      " << myJetCalibrator.getIntPt()      << std::endl;  
 std::cout << ">>>>> JetCalibrator::IntEta     " << myJetCalibrator.getIntEta()     << std::endl;  
 std::cout << ">>>>> JetCalibrator::NParameter " << myJetCalibrator.getNParameter() << std::endl;  
 std::cout << ">>>>> JetCalibrator::MResonance " << myJetCalibrator.getMResonance() << std::endl;  

 TFile outFile(outputFileName.c_str(),"RECREATE");
 TTree outTree("outTree","outTree");
 double t_M_Reco;
 std::vector<double>* t_pT_Reco = new std::vector<double>;
 std::vector<double>* t_pT_MC = new std::vector<double>;
 std::vector<double>* t_Eta_Reco = new std::vector<double>;
 int t_Cycle_num; //---- 0 = Before, 1 = After
 int t_Indip; //---- 0 = No Indip, 1 = Indip
 
 outTree.Branch("t_pT_Reco","std::vector<double>",&t_pT_Reco);
 outTree.Branch("t_pT_MC","std::vector<double>",&t_pT_MC);
 outTree.Branch("t_Eta_Reco","std::vector<double>",&t_Eta_Reco);
 outTree.Branch("t_M_Reco",&t_M_Reco,"t_M_Reco/D");
 outTree.Branch("t_Cycle_num",&t_Cycle_num,"t_Cycle_num/I");
 outTree.Branch("t_Indip",&t_Indip,"t_Indip/I");
 
 TH2F hKK_num("hKK_num","hKK_num",myJetCalibrator.getIntPt(),myJetCalibrator.getPtMin(),myJetCalibrator.getPtMax(),myJetCalibrator.getIntEta(),0,myJetCalibrator.getEtaMax()); //---- correction function K(eta) x K(pT) ----
 std::vector<TH2F> hKK_vect;
 std::vector<TH2F> hKK_err_vect;
 
 
 
 
 
 
 std::cout << ">>>>> tree::entries " << chain -> GetEntries()  << std::endl;
 entryMAX = std::min (static_cast<int>(entryMAX),static_cast<int>(chain -> GetEntries()));
 
 double start, end;
 
 
 ///===============================
 ///==== Filling JetCalibrator ====
 
 std::vector<ROOT::Math::XYZTVector>* mcF_fromV1 = new std::vector<ROOT::Math::XYZTVector>;
 std::vector<ROOT::Math::XYZTVector>* mcF_fromV2 = new std::vector<ROOT::Math::XYZTVector>;
 start = clock();
 for(int iEvent = entryMIN ; iEvent < entryMAX ; ++iEvent)
 {
  reader.GetEntry(iEvent);
  if((iEvent%entryMOD) == 0) std::cout << ">>>>> analysis::GetEntry " << iEvent << std::endl;   
  
  std::vector<ROOT::Math::XYZTVector>* mcV1 = reader.Get4V("mcV1");
  std::vector<ROOT::Math::XYZTVector>* mcV2 = reader.Get4V("mcV2");
  
  std::vector<float>* mcV1_charge = reader.GetFloat("mcV1_charge");
  std::vector<float>* mcV2_charge = reader.GetFloat("mcV2_charge");
  
  std::vector<ROOT::Math::XYZTVector>* mcF1_fromV1 = reader.Get4V("mcF1_fromV1");
  std::vector<ROOT::Math::XYZTVector>* mcF1_fromV2 = reader.Get4V("mcF1_fromV2");
  std::vector<ROOT::Math::XYZTVector>* mcF2_fromV1 = reader.Get4V("mcF2_fromV1");
  std::vector<ROOT::Math::XYZTVector>* mcF2_fromV2 = reader.Get4V("mcF2_fromV2");
  
  std::vector<float>* mcF1_fromV1_pdgId = reader.GetFloat("mcF1_fromV1_pdgId");
  std::vector<float>* mcF1_fromV2_pdgId = reader.GetFloat("mcF1_fromV2_pdgId");
  std::vector<float>* mcF2_fromV1_pdgId = reader.GetFloat("mcF2_fromV1_pdgId");
  std::vector<float>* mcF2_fromV2_pdgId = reader.GetFloat("mcF2_fromV2_pdgId");
  
  std::vector<ROOT::Math::XYZTVector>* jets = reader.Get4V("jets");
  
  mcF_fromV1->clear();
  mcF_fromV2->clear();
  mcF_fromV1->push_back(mcF1_fromV1->at(0));
  mcF_fromV1->push_back(mcF2_fromV1->at(0));
  mcF_fromV2->push_back(mcF1_fromV2->at(0));
  mcF_fromV2->push_back(mcF2_fromV2->at(0));
    
  std::vector<int> matchIt;
  int matched = 0;
  
  std::pair<int,int> decayMC = GetMCDecayChannel(mcF1_fromV1_pdgId->at(0),mcF2_fromV1_pdgId->at(0),mcF1_fromV2_pdgId->at(0),mcF2_fromV2_pdgId->at(0));
   
  if (decayMC.first == 2 && decayMC.second == 1){
   ///==== emu - quark ======== < 2 , 1 >
   matched = GetMatching<ROOT::Math::XYZTVector,ROOT::Math::XYZTVector>(*jets,*mcF_fromV2,0.3,0.1,2.0,&matchIt);
  }
  if (decayMC.first == 2 && decayMC.second == 2){
   ///==== quark - emu ======== < 2 , 2 >
   matched = GetMatching<ROOT::Math::XYZTVector,ROOT::Math::XYZTVector>(*jets,*mcF_fromV1,0.3,0.1,2.0,&matchIt);
  }
  
  if (matched > 0){
   if (matched == 2){
    std::pair<ROOT::Math::XYZTVector,ROOT::Math::XYZTVector> InputJetPair(jets->at(matchIt.at(0)),jets->at(matchIt.at(1)));
    
    ///--------------------------------------
    bool okJet = myJetCalibrator.AddJetPair(InputJetPair);
    ///--------------------------------------   
    if (okJet){
     hKK_num.Fill(jets->at(matchIt.at(0)).Pt(),jets->at(matchIt.at(0)).Eta());
     hKK_num.Fill(jets->at(matchIt.at(1)).Pt(),jets->at(matchIt.at(1)).Eta());
    }
   }
  }
 } //loop over the events
 


///==== end Filling JetCalibrator ====
///===================================


///======================
///==== minimization ====

int nCycle = gConfigParser -> readIntOption("Calibration::nCycle");
int Algorithm = gConfigParser -> readIntOption("Calibration::Algorithm");

std::cout << ">>>>> Calibration::nCycle " << nCycle << std::endl;   

if (Algorithm == 0) std::cout << ">>>>> Calibration::Algorithm UpdateMatrixInversion" << std::endl;   
if (Algorithm == 1) std::cout << ">>>>> Calibration::Algorithm UpdateRUL3" << std::endl;   
if (Algorithm == 2) std::cout << ">>>>> Calibration::Algorithm UpdateL3 ----------> Be Careful!" << std::endl;   
if (Algorithm == 3) std::cout << ">>>>> Calibration::Algorithm UpdateKUpdate ----------> Be Careful!" << std::endl;   
if (Algorithm == 4) std::cout << ">>>>> Calibration::Algorithm UpdateRUFit" << std::endl;   
if (Algorithm == 5) std::cout << ">>>>> Calibration::Algorithm UpdateSFit" << std::endl;   
if (Algorithm == 6) std::cout << ">>>>> Calibration::Algorithm UpdateMIB" << std::endl;   
if (Algorithm == 7) std::cout << ">>>>> Calibration::Algorithm UpdateSRooFit" << std::endl;   
if (Algorithm == 8) std::cout << ">>>>> Calibration::Algorithm UpdateSL3" << std::endl;   

for (int iCycle=0; iCycle< nCycle; iCycle++) { 
 std::cerr << "Cycle = " << iCycle << std::endl;
 std::cerr << "chi2 = " << myJetCalibrator.getChi2() << std::endl;
 
 ///------------------------------------------------------------
 if (Algorithm == 0) myJetCalibrator.UpdateMatrixInversion();
 if (Algorithm == 1) myJetCalibrator.UpdateRUL3();
 if (Algorithm == 2) myJetCalibrator.UpdateL3();
 if (Algorithm == 3) myJetCalibrator.UpdateKUpdate();
 if (Algorithm == 4) myJetCalibrator.UpdateRUFit();
 if (Algorithm == 5) myJetCalibrator.UpdateSFit();
 if (Algorithm == 6) myJetCalibrator.UpdateMIB();
 if (Algorithm == 7) myJetCalibrator.UpdateSRooFit();
 if (Algorithm == 8) myJetCalibrator.UpdateSL3();
 ///------------------------------------------------------------
 
 std::ostringstream oss;
 oss << "hKK_" << iCycle;
 std::string nameHisto(oss.str());
 TH2F hKK_tmp(nameHisto.c_str(),nameHisto.c_str(),myJetCalibrator.getIntPt(),myJetCalibrator.getPtMin(),myJetCalibrator.getPtMax(),myJetCalibrator.getIntEta(),0,myJetCalibrator.getEtaMax()); //---- correction function K(eta) x K(pT) ----

 oss << "_err";
 std::string nameHistoErr(oss.str());
 
 TH2F hKK_err_tmp(nameHistoErr.c_str(),nameHistoErr.c_str(),myJetCalibrator.getIntPt(),myJetCalibrator.getPtMin(),myJetCalibrator.getPtMax(),myJetCalibrator.getIntEta(),0,myJetCalibrator.getEtaMax()); //---- error on correction function K(eta) x K(pT) ----
 
 
 for (int iEta=0; iEta<myJetCalibrator.getIntEta(); iEta++){
  for (int iPt=0; iPt<myJetCalibrator.getIntPt(); iPt++){
   hKK_tmp.SetBinContent(iPt+1,iEta+1,myJetCalibrator.getKK(myJetCalibrator.GetInt(iPt,iEta)));
   hKK_err_tmp.SetBinContent(iPt+1,iEta+1,myJetCalibrator.getKKErr(myJetCalibrator.GetInt(iPt,iEta)));   
   //    std::cerr << "KK[" << iPt << "][" << iEta << "] = " << myJetCalibrator.getKK(myJetCalibrator.GetInt(iPt,iEta)) << std::endl;
  }
 }
 std::cerr << "JetCalibrator::chi2 = " << myJetCalibrator.getChi2() << std::endl;
 hKK_vect.push_back(hKK_tmp);  
 hKK_err_vect.push_back(hKK_err_tmp);  
}

///==== end minimization ====
///==========================



///==============
///==== test ====

///---- same sample as before ----

for(int iEvent = entryMIN ; iEvent < entryMAX ; ++iEvent)
{
 reader.GetEntry (iEvent) ;
 std::vector<ROOT::Math::XYZTVector>* mcV1 = reader.Get4V("mcV1");
 std::vector<ROOT::Math::XYZTVector>* mcV2 = reader.Get4V("mcV2");
 
 std::vector<float>* mcV1_charge = reader.GetFloat("mcV1_charge");
 std::vector<float>* mcV2_charge = reader.GetFloat("mcV2_charge");
 
 std::vector<ROOT::Math::XYZTVector>* mcF1_fromV1 = reader.Get4V("mcF1_fromV1");
 std::vector<ROOT::Math::XYZTVector>* mcF1_fromV2 = reader.Get4V("mcF1_fromV2");
 std::vector<ROOT::Math::XYZTVector>* mcF2_fromV1 = reader.Get4V("mcF2_fromV1");
 std::vector<ROOT::Math::XYZTVector>* mcF2_fromV2 = reader.Get4V("mcF2_fromV2");
 
 std::vector<float>* mcF1_fromV1_pdgId = reader.GetFloat("mcF1_fromV1_pdgId");
 std::vector<float>* mcF1_fromV2_pdgId = reader.GetFloat("mcF1_fromV2_pdgId");
 std::vector<float>* mcF2_fromV1_pdgId = reader.GetFloat("mcF2_fromV1_pdgId");
 std::vector<float>* mcF2_fromV2_pdgId = reader.GetFloat("mcF2_fromV2_pdgId");
 
 std::vector<ROOT::Math::XYZTVector>* jets = reader.Get4V("jets");
 
 mcF_fromV1->clear();
 mcF_fromV2->clear();
 mcF_fromV1->push_back(mcF1_fromV1->at(0));
 mcF_fromV1->push_back(mcF2_fromV1->at(0));
 mcF_fromV2->push_back(mcF1_fromV2->at(0));
 mcF_fromV2->push_back(mcF2_fromV2->at(0));
 
 std::vector<int> matchIt;
 int matched = 0;
 
 std::pair<int,int> decayMC = GetMCDecayChannel(mcF1_fromV1_pdgId->at(0),mcF2_fromV1_pdgId->at(0),mcF1_fromV2_pdgId->at(0),mcF2_fromV2_pdgId->at(0));
 
 if (decayMC.first == 2 && decayMC.second == 1){
  ///==== emu - quark ======== < 2 , 1 >
  matched = GetMatching<ROOT::Math::XYZTVector,ROOT::Math::XYZTVector>(*jets,*mcF_fromV2,0.3,0.1,2.0,&matchIt);
 }
 if (decayMC.first == 2 && decayMC.second == 2){
  ///==== quark - emu ======== < 2 , 2 >
  matched = GetMatching<ROOT::Math::XYZTVector,ROOT::Math::XYZTVector>(*jets,*mcF_fromV1,0.3,0.1,2.0,&matchIt);
 }
 
 
 if (matched > 0){
  if (matched == 2){
   int iPt1 = myJetCalibrator.GetIntPt(jets->at(matchIt.at(0)).Pt());
   int iEta1 = myJetCalibrator.GetIntEta(jets->at(matchIt.at(0)).Eta());
   
   int iPt2 = myJetCalibrator.GetIntPt(jets->at(matchIt.at(1)).Pt());
   int iEta2 = myJetCalibrator.GetIntEta(jets->at(matchIt.at(0)).Eta());
   
   double M_temp = (jets->at(matchIt.at(0)) + jets->at(matchIt.at(1))).M();
   //---- data not used, out of range for KK!
   if ((iPt1 != -1) && (iPt2 != -1) && (iEta1 != -1.) && (iEta2 != -1)) {
    
    M_temp = M_temp * sqrt(myJetCalibrator.getKK(myJetCalibrator.GetInt(iPt1,iEta1)) * myJetCalibrator.getKK(myJetCalibrator.GetInt(iPt2,iEta2)));    
    t_M_Reco = M_temp;    
    t_Eta_Reco->push_back(jets->at(matchIt.at(0)).Eta());
    t_Eta_Reco->push_back(jets->at(matchIt.at(1)).Eta());
    t_pT_Reco->push_back(jets->at(matchIt.at(0)).Pt() * myJetCalibrator.getKK(myJetCalibrator.GetInt(iPt1,iEta1)));
    t_pT_Reco->push_back(jets->at(matchIt.at(1)).Pt() * myJetCalibrator.getKK(myJetCalibrator.GetInt(iPt2,iEta2))); 
    
    if (decayMC.second == 2){  ///==== quark - emu ======== < 2 , 2 >
     t_pT_MC->push_back(mcF_fromV1->at(0).Pt());
     t_pT_MC->push_back(mcF_fromV1->at(1).Pt());
    }
    else {///==== emu - quark ======== < 2 , 1 >
     t_pT_MC->push_back(mcF_fromV2->at(0).Pt());
     t_pT_MC->push_back(mcF_fromV2->at(1).Pt());
    }
    t_Cycle_num = 1; //---- after
    t_Indip = 0; //---- No Indip
    outTree.Fill();   
    t_pT_Reco->clear();
      
    t_Cycle_num = 0; //---- before
    t_Indip = 0; //---- No Indip
    M_temp = (jets->at(matchIt.at(0)) + jets->at(matchIt.at(1))).M();
    t_M_Reco = M_temp; 
    t_pT_Reco->push_back(jets->at(matchIt.at(0)).Pt());
    t_pT_Reco->push_back(jets->at(matchIt.at(1)).Pt()); 
    outTree.Fill();
    
    t_pT_Reco->clear();
    t_pT_MC->clear();   
    t_Eta_Reco->clear();
   }
  }
 } 
}



///---- independent sample ----

int entryMAXTest = gConfigParser -> readIntOption("Test::entryMAX");
int entryMINTest = gConfigParser -> readIntOption("Test::entryMIN");

entryMAXTest = std::min (static_cast<int>(entryMAXTest),static_cast<int>(chain -> GetEntries()));

for(int iEvent = entryMINTest ; iEvent < entryMAXTest ; ++iEvent)
{
 reader.GetEntry (iEvent) ;
 std::vector<ROOT::Math::XYZTVector>* mcV1 = reader.Get4V("mcV1");
 std::vector<ROOT::Math::XYZTVector>* mcV2 = reader.Get4V("mcV2");
 
 std::vector<float>* mcV1_charge = reader.GetFloat("mcV1_charge");
 std::vector<float>* mcV2_charge = reader.GetFloat("mcV2_charge");
 
 std::vector<ROOT::Math::XYZTVector>* mcF1_fromV1 = reader.Get4V("mcF1_fromV1");
 std::vector<ROOT::Math::XYZTVector>* mcF1_fromV2 = reader.Get4V("mcF1_fromV2");
 std::vector<ROOT::Math::XYZTVector>* mcF2_fromV1 = reader.Get4V("mcF2_fromV1");
 std::vector<ROOT::Math::XYZTVector>* mcF2_fromV2 = reader.Get4V("mcF2_fromV2");
 
 std::vector<float>* mcF1_fromV1_pdgId = reader.GetFloat("mcF1_fromV1_pdgId");
 std::vector<float>* mcF1_fromV2_pdgId = reader.GetFloat("mcF1_fromV2_pdgId");
 std::vector<float>* mcF2_fromV1_pdgId = reader.GetFloat("mcF2_fromV1_pdgId");
 std::vector<float>* mcF2_fromV2_pdgId = reader.GetFloat("mcF2_fromV2_pdgId");
 
 std::vector<ROOT::Math::XYZTVector>* jets = reader.Get4V("jets");
 
 mcF_fromV1->clear();
 mcF_fromV2->clear();
 mcF_fromV1->push_back(mcF1_fromV1->at(0));
 mcF_fromV1->push_back(mcF2_fromV1->at(0));
 mcF_fromV2->push_back(mcF1_fromV2->at(0));
 mcF_fromV2->push_back(mcF2_fromV2->at(0));
 
 std::vector<int> matchIt;
 int matched = 0;

 std::pair<int,int> decayMC = GetMCDecayChannel(mcF1_fromV1_pdgId->at(0),mcF2_fromV1_pdgId->at(0),mcF1_fromV2_pdgId->at(0),mcF2_fromV2_pdgId->at(0));
 
 if (decayMC.first == 2 && decayMC.second == 1){
  ///==== emu - quark ======== < 2 , 1 >
  matched = GetMatching<ROOT::Math::XYZTVector,ROOT::Math::XYZTVector>(*jets,*mcF_fromV2,0.3,0.1,2.0,&matchIt);
 }
 if (decayMC.first == 2 && decayMC.second == 2){
  ///==== quark - emu ======== < 2 , 2 >
  matched = GetMatching<ROOT::Math::XYZTVector,ROOT::Math::XYZTVector>(*jets,*mcF_fromV1,0.3,0.1,2.0,&matchIt);
 }
 
 if (matched > 0){
  if (matched == 2){
   int iPt1 = myJetCalibrator.GetIntPt(jets->at(matchIt.at(0)).Pt());
   int iEta1 = myJetCalibrator.GetIntEta(jets->at(matchIt.at(0)).Eta());
   
   int iPt2 = myJetCalibrator.GetIntPt(jets->at(matchIt.at(1)).Pt());
   int iEta2 = myJetCalibrator.GetIntEta(jets->at(matchIt.at(0)).Eta());
   double M_temp = (jets->at(matchIt.at(0)) + jets->at(matchIt.at(1))).M();
   //---- data not used, out of range for KK!
   if ((iPt1 != -1) && (iPt2 != -1) && (iEta1 != -1.) && (iEta2 != -1)) {
    
    M_temp = M_temp * sqrt(myJetCalibrator.getKK(myJetCalibrator.GetInt(iPt1,iEta1)) * myJetCalibrator.getKK(myJetCalibrator.GetInt(iPt2,iEta2)));    
    t_M_Reco = M_temp;    
    t_Eta_Reco->push_back(jets->at(matchIt.at(0)).Eta());
    t_Eta_Reco->push_back(jets->at(matchIt.at(1)).Eta());
    t_pT_Reco->push_back(jets->at(matchIt.at(0)).Pt() * myJetCalibrator.getKK(myJetCalibrator.GetInt(iPt1,iEta1)));
    t_pT_Reco->push_back(jets->at(matchIt.at(1)).Pt() * myJetCalibrator.getKK(myJetCalibrator.GetInt(iPt2,iEta2))); 
    
    if (decayMC.second == 2){  ///==== quark - emu ======== < 2 , 2 >
     t_pT_MC->push_back(mcF_fromV1->at(0).Pt());
     t_pT_MC->push_back(mcF_fromV1->at(1).Pt());
    }
    else {///==== emu - quark ======== < 2 , 1 >
     t_pT_MC->push_back(mcF_fromV2->at(0).Pt());
     t_pT_MC->push_back(mcF_fromV2->at(1).Pt());
    }
    t_Cycle_num = 1; //---- after
    t_Indip = 1; //---- Yes Indip
    outTree.Fill();   
    t_pT_Reco->clear();
    
    t_Cycle_num = 0; //---- before
    t_Indip = 1; //---- Yes Indip
    M_temp = (jets->at(matchIt.at(0)) + jets->at(matchIt.at(1))).M();
    t_M_Reco = M_temp; 
    t_pT_Reco->push_back(jets->at(matchIt.at(0)).Pt());
    t_pT_Reco->push_back(jets->at(matchIt.at(1)).Pt());   
    outTree.Fill();
    
    t_pT_Reco->clear();
    t_pT_MC->clear();   
    t_Eta_Reco->clear();
   }
  }
 } 
}



///==== end test ====
///==================


delete mcF_fromV1;
delete mcF_fromV2;



for (int iHisto=0; iHisto<hKK_vect.size(); iHisto++){
 hKK_vect.at(iHisto).Write();
 hKK_err_vect.at(iHisto).Write();
} 

outFile.Write();   

end = clock();
std::cout <<"Time = " <<  ((double) (end - start)) << " (a.u.)" << std::endl;

delete t_pT_Reco;
delete t_pT_MC;
delete t_Eta_Reco;

return 0;
}