/**
* TOFScan
* Author  Nagni
* Version 1.2
* Modified by G.De Rosa
* Date 27 Apr 2006
* Modified by G.De Rosa
* Date 03 Jul 2006
*
* Description:
* Describe the performance of the TOF.
*
* Parameters:
* 	TString base            - the path to the root directory for the specific Pamela unpack session 
* 	TString outDirectory    - the path where to save the output image (Default = base) 
*       TString format          - the format which will be used fo rsave the produced images (Default = "gif") 
*/

#include <TROOT.h>
#include <TH1.h>
#include <TFile.h>
#include <TObjArray.h>
#include <TString.h>
#include <TObjString.h>
#include <TTree.h>
#include <TBranch.h>
#include <TGraph.h>
#include <TStyle.h>
#include <TH2S.h>
#include <TPaveText.h>
#include <TCanvas.h>
#include <physics/tof/TofEvent.h>


#include <iostream>
using namespace std;

void TofScan(TString base, TString outDirectory = "", TString format = ""){
   
   std::stringstream sst;
   if (outDirectory == "") outDirectory = base.Data();
   TString filename = ((TObjString*)base.Tokenize('/')->Last())->GetString();

   TFile *file  =new TFile(base.Data()) ;
   if (!file){
    printf("file not Found \n");
    return;
   }

   TTree *PhysicsTr = (TTree*)file->Get("Physics");
   TBranch *TofBr = PhysicsTr->GetBranch("Tof");
   pamela::tof::TofEvent *tofEvent = 0;
   PhysicsTr->SetBranchAddress("Tof", &tofEvent);
   
   Long64_t nevents    = TofBr->GetEntries();
   if (nevents <= 0) {
     printf("nevents = %llu \n", nevents);
     file->Close();
     return;
   }

   /*
    * Array to convert hdc/adc to the real Photomultiplier
    * The array rows definitions are:
    * tof[0][] = chxxA (strip or channel xxA)
    * tof[1][] = hbxxA (halfboard xxA)
    * tof[2][] = chxxB (strip or channel xxB)
    * tof[3][] = hbxxB (halfboard xxB)
    *
    * Each single row is a sequence of photomultipliers in this shape
    * - The elements from  0 to  7  correspond to S11_1->S11_8
    * - The elements from  8 to 13  correspond to S12_1->S12_6
    * - The elements from 14 to 15  correspond to S21_1->S21_2
    * - The elements from 16 to 17  correspond to S22_1->S22_2
    * - The elements from 18 to 20  correspond to S31_1->S31_3
    * - The elements from 21 to 23  correspond to S32_1->S32_3
    * 
    * Example: 
    * -------> the tdc of the S12_3B photomultiplier correspond to tdc[(tof[2][10])][(tof[3][10])] 
    * -------> the tdc of the S31_3A photomultiplier correspond to tdc[(tof[0][20])][(tof[1][20])] 
    */
   short tof[4][24] = {
     {4, 4,  4,  4,  1,  1, 2, 2,  3,  3, 3, 3,  3,  3, 1, 1,  1,  1, 2, 3,  3, 3, 3,  4},
     {1, 3,  5,  7, 10, 12, 2, 4,  2,  4, 6, 8, 10, 12, 1, 5,  3,  9, 7, 9, 11, 1, 5,  9},
     {2, 2,  2,  2,  1,  1, 1, 1,  4,  4, 4, 4,  4,  4, 2, 1,  2,  1, 2, 2,  2, 3, 3,  4},
     {6, 8, 12, 10,  8,  6, 4, 2, 12, 10, 8, 6,  4,  2, 9, 7, 11, 11, 5, 3,  1, 3, 7, 11}
   };
   
   TString photoS[48] = {
     "S11_1A", "S11_1B", "S11_2A", "S11_2B", "S11_3A", "S11_3B", "S11_4A", "S11_4B", 
     "S11_5A", "S11_5B", "S11_6A", "S11_6B", "S11_7A", "S11_7B", "S11_8A", "S11_8B", 
     "S12_1A", "S12_1B", "S12_2A", "S12_2B", "S12_3A", "S12_3B", "S12_4A", "S12_4B", "S12_5A",  "S12_5B", "S12_6A", "S12_6B",
     "S21_1A", "S21_1B", "S21_2A", "S21_2B", 
     "S22_1A", "S22_1B", "S22_2A", "S22_2B",
     "S31_1A", "S31_1B", "S31_2A", "S31_2B", "S31_3A", "S31_3B", 
     "S32_1A", "S32_1B", "S32_2A", "S32_2B", "S32_3A", "S32_3B"
   };
   
   const Int_t nh = 48;
   TH1F *htdc[nh];
   TH1F *hadc[nh];
   
   TObjArray *hhtdc = new TObjArray(nh);
   TObjArray *hhadc = new TObjArray(nh);
   char tdcname[48]="";
   char adcname[48]="";
   
   int j  = 0;
   int k  = 0;
   int z  = 0;
   int ch = 0;
   int hb = 0;
   int ind =0;


   for (int i=0; i < nevents; i++){

     TofBr->GetEntry(i);

     k = 0;
     while (k < 24){
       j = 0;
       while (j < 2){
	 ch = tof[2*j][k]     - 1;
	 hb = tof[2*j + 1][k] - 1;
	 ind = 2*k + j;

	 if(i==0){
	   sprintf(tdcname,"TDChist%4.4d",ind);
	   sprintf(adcname,"ADChist%4.4d",ind);
       
	   htdc[ind] = new TH1F(tdcname,tdcname,409,0,4096);
	   hadc[ind] = new TH1F(adcname,adcname,409,0,4096);
       
	   hhtdc->Add(htdc[ind]);
	   hhadc->Add(hadc[ind]);
	 }

	 htdc[ind]->Fill(tofEvent->tdc[ch][hb]);
	 hadc[ind]->Fill(tofEvent->adc[ch][hb]);
	 
	 j++;
       }
       k++;
     }
   }
   
   float *X       = new float[48];
   float *means   = new float[48];
   float *entries = new float[48];
   int *entriestdc = new int[48];
   int *entriesadc = new int[48];
   
   const char *saveas = format;
   
   int i=0;
   
   gStyle->SetStatW(0.4);
   gStyle->SetStatH(0.4);
   gStyle->SetOptStat("nmri");
   gStyle->SetTitleH(0.10);
   gStyle->SetTitleW(0.96);
   
   TCanvas *SCanvas = new TCanvas("SCanvas","SCanvas", 1280, 1024);
   SCanvas->Divide(4,2);

   j = 0;
   while (j < 12){
     k = 0;
     z = 0;
     if (gROOT->IsBatch()) {
       SCanvas = new TCanvas("SCanvas","SCanvas", 1280, 1024);
       SCanvas->Divide(4,2);
     } else {
       if (j > 0) SCanvas->DrawClone();
     }
     
     
     while(k < 4){
       if (k > 1) z = 2;
       i = j*4 + k;
       X[i] = i;
       
       SCanvas->cd(k+3+z);
       htdc[i] = (TH1F*)hhtdc->At(i);  
       entriestdc[i] = (Int_t)htdc[i]->Integral();
       sst.str("");
       sst << "TDC - " << photoS[i].Data() << " (Nev < 4096 = " << entriestdc[i] << ")";
       htdc[i]->SetTitle(sst.str().c_str());
       htdc[i]->SetTitleSize(10);
       htdc[i]->SetAxisRange(690,1510);
       htdc[i]->DrawCopy();
       htdc[i]->ComputeIntegral();
       entries[i] = htdc[i]->Integral();
       
       SCanvas->cd(k+1+z);       
       hadc[i] = (TH1F*)hhadc->At(i);
       entriesadc[i] = (Int_t)hadc[i]->Integral();
       sst.str("");
       sst << "ADC - " << photoS[i].Data() << " (Nev < 4096 = " << entriesadc[i] << ")";
       hadc[i]->SetTitle(sst.str().c_str());
       hadc[i]->SetAxisRange(-10,710); 
       hadc[i]->DrawCopy();
       means[i]   = hadc[i]->GetMean();
       
       k++;
     }
     

     if ( !strcmp(saveas,"ps") ) {
       sst.str("");
       sst << outDirectory.Data() << filename.Data() << "TOFScan.ps(";
       SCanvas->Print(sst.str().c_str());
     } else {
       sst.str("");
       sst << outDirectory.Data() << filename.Data() << "TOFScan" << j+1 << "." << saveas;
       SCanvas->SaveAs(sst.str().c_str());
       
     }
     j++;
   }

   if (gROOT->IsBatch()) SCanvas->Close();
   
   /*
    * This Canvas will represent a summary of the performances for TOF TDC/ADC channels
    */
   TCanvas *performanceCanvas = new TCanvas("performanceCanvas","performanceCanvas", 1280, 1024);
   performanceCanvas->Divide(1,2);
   
   gStyle->SetTitleW(.9);

   performanceCanvas->cd(1);
   TGraph *adcMeans   = new TGraph(48, X, means);
   sst.str("");
   sst << "ADCMean"  << " - Data in " << base.Data() << " - Nevents in the run = " << nevents;
   adcMeans->SetTitle(sst.str().c_str());
   adcMeans->SetFillColor(35);
   adcMeans->GetXaxis()->SetTitle("Photomultipliers");
   adcMeans->GetXaxis()->CenterTitle();
   adcMeans->GetXaxis()->SetLimits(-0.5, 47.5);
   adcMeans->GetYaxis()->SetTitle("ADCMean");
   adcMeans->GetYaxis()->CenterTitle();	
   adcMeans->Draw("AB");
   
   performanceCanvas->cd(2);
   TGraph *tdcEntries = new TGraph(48, X, entries);
   sst.str("");
   sst << "TDCEntries"  << " - Data in " << base.Data() << " - Nevents in the run = " << nevents;
   tdcEntries->SetTitle(sst.str().c_str());
   tdcEntries->SetFillColor(35);
   tdcEntries->GetXaxis()->SetTitle("Photomultipliers");
   tdcEntries->GetXaxis()->CenterTitle();
   tdcEntries->GetXaxis()->SetLimits(-0.5, 47.5);
   tdcEntries->GetYaxis()->SetTitle("TDCIntegral");
   tdcEntries->GetYaxis()->CenterTitle();	
   tdcEntries->Draw("AB");
   
   //------print the ps

   if ( !strcmp(saveas,"ps") ) {
     sst.str("");
     sst << outDirectory.Data() << filename.Data() << "TOFScan.ps)";
     performanceCanvas->Print(sst.str().c_str());
     
   } else {
     sst.str("");
     sst << outDirectory.Data() << filename.Data() << "TOFScan13." << saveas;
     performanceCanvas->SaveAs(sst.str().c_str());
   }
   if (gROOT->IsBatch()) {
     SCanvas->Close();
     performanceCanvas->Close();
   }

}

int main(int argc, char* argv[]){
  TString path;
  TString outDir        ="./";
  TString format        ="ps";
    
 if (argc < 2){
    printf("You have to insert at least the file to analyze \n");
    printf("Try '--help' for more information. \n");
    exit(1);
  }  

  if (!strcmp(argv[1], "--help")){
        printf( "Usage: TofScan FILE [OPTION] \n");
        printf( "\t --help                  Print this help and exit \n");	
        printf( "\t -outDir[path]           Path where to put the output [default ./] \n");
        printf( "\t -format[ps]             Format for output files [default 'ps'] \n");
        exit(1);
  }


  path=argv[1];

   for (int i = 2; i < argc; i++){

     if (!strcmp(argv[i], "-outDir")){
       if (++i >= argc){
	 printf( "-outDir needs arguments. \n");
	 printf( "Try '--help' for more information. \n");
	 exit(1);
	} 
       else{
	 outDir = argv[i];
	 continue;
       }
     }
     
     
     
     if (!strcmp(argv[i], "-format")){
       if (++i >= argc){
	 printf( "-format needs arguments. \n");
	 printf( "Try '--help' for more information. \n");
	 exit(1);
       } 
       else{
	 format = argv[i];
	 continue;
       }
     }
  }

   TofScan(argv[1], outDir, format);

}
