/**
* Header_Scan
* Author  Nagni
* version 1.0
*
* Version 1.1 - 28 December 2004
* If outList does not exist the function exit to prompt
* If nevents = 0 the function exit to promt
*
* Version 1.2 - 3 January 2005
* Two canvases are created to see the graphs better
*
* Version 1.25 - 13 January 2005
* Changed Int_t to Float because of variable range size
* (UInt_t has been excluded beacuse of uncompatibility with TGraph)
*
* version 1.3  - 22 February 2005 - Nagni
* For compatibility with batch mode excution:
* 1) Added "include <iostream>" and "using namespace std" 
* 2) Removed gROOT->Reset()
*
* Version 1.4
* Date 08 March 2005
* Added "format" parameter for saving the produced image in various formats
* (for a complete list of types refer to TPad::SaveAs method)
*
* Version 1.5
* Date 09 February 2006 - Marcelli
* Update to work with new Yoda output
*
* Version 1.6
* Date 27 February 2006 - Marcelli
* For compilation: 
*     Added function "int main(int argc, char* argv[])"
*
*
* Description: This script creates two canvases with five pads. The first pad shows packetID variable (for all packets) vs. OBT.
*     	       The second pad shows the number of physic packets vs. OBT. The third pad shows the lenght of Physic packets (byte) vs. OBT.
*              The fourth pad shows the packetcounter of physic packets vs. OBT. The fifth pad shows PacketCounter vs. File Offset.
*
* Parameters:
* 	       TSTring base          - the path to the root directory for the specific Pamela unpack session
*                                      There is no default value, without this input the program will not run
*              TString outDir        - the path where to save the output image (Default = ./) 
*              TString format        - the format which will be used fo rsave the produced images (Default = "jpg") 
*
*
* Version 1.7
* Date 16 June 2006 - Malvezzi
*
* Description of changes:
*                         Implementation of the case: numebr of events <= 0.
*                         Remove graph "grPcktId1"; see PacketScan for the same information.
*             Fixed bugs: for a large namber of events is not possible to have vectors, so I have subsituted graphs with histograms
*                         or divided the graphs in more than one canvas.
*
* Version 1.8
* Date 8 August 2006 - Malvezzi
*
* Description: changed the scale in the second and third graph of the first canvas; added a pad of text in the second canvas 
*
*/


#include <fstream>
#include <math.h>
#include "TLatex.h"
#include "TF1.h"
#include "TPaveText.h"
#include "TMultiGraph.h"
#include <sstream>
#include <iostream>
#include "TString.h"
#include "TStyle.h"
#include "TFile.h"
#include "TList.h"
#include "TTree.h"
#include "TObjString.h"
#include "TCanvas.h"
#include "TGraph.h"
#include "TH1F.h"
#include "TGaxis.h"
#include "EventHeader.h"
#include "PscuHeader.h"

using namespace std;

void HeaderScan(TString base, TString outDir, TString format)
{

  //------------------- Variables initilization -------------------------//
  Long64_t nevents=0; 
  ULong_t lastime, firstime, primotempo, ultimotempo, primoffset=500000000, ultimoffset=100000000;
  double obmin=0.;
  double obmax=0.; 
  stringstream oss, oss1, oss2, oss3, noentries, stringa;
  //------- load root file --------------
  TFile *file = new TFile(base.Data());
  if (!file){
    printf("No such file in the directory has been found");
    return;
  }
  
  TTree *PhysicsTr = (TTree*)file->Get("Physics");
  TBranch *headBr = PhysicsTr->GetBranch("Header");

  pamela::EventHeader  *eh   = 0;
  pamela::PscuHeader   *ph   = 0;

  PhysicsTr->SetBranchAddress("Header", &eh);

  nevents = headBr->GetEntries();

  TString filename = ((TObjString*)base.Tokenize('/')->Last())->GetString(); 
  filename = ((TObjString*)filename.Tokenize('.')->First())->GetString();

  //----------- If nevents < = 0 ---------------------------------/
  if (nevents<=0) {
    printf("nevents = %i \n", nevents);
    printf(" \n");

    TCanvas *canv = new TCanvas("No entries", "No entries ", 400, 200);
    canv->SetFillColor(10);
    canv->cd();

    TLatex *l = new TLatex();
    l->SetTextAlign(12);
    l->SetTextSize(0.15);
    l->SetTextColor(2);
    noentries.str("");
    noentries<< "HeaderScan_QL:";
    l->DrawLatex(0.05, 0.7, noentries.str().c_str()); 
    noentries.str("");
    noentries<< "No Physics entries for this files";
    l->DrawLatex(0.05, 0.5, noentries.str().c_str()); 

    if (outDir == "./") {
      oss.str("");
      oss << filename.Data() << "_HeaderScan_QL." << format.Data();
    } else {
      oss.str("");
      oss << outDir.Data() << filename.Data() << "_HeaderScan_QL." << format.Data();
    }
  
    canv->Update();
    canv->SaveAs(oss.str().c_str()); 

    return;
  }

  //-------------- to know the max and min OBT ----------------------------//
   headBr->GetEntry(0);
   ph = eh->GetPscuHeader();
   firstime = ph->GetOrbitalTime();

   for (Int_t i = 0; i < nevents; i++){
    headBr->GetEntry(i);
    ph = eh->GetPscuHeader();
    if((ph->GetOrbitalTime()) <= firstime) firstime=ph->GetOrbitalTime();
    if((ph->GetOrbitalTime()) >= lastime) lastime=ph->GetOrbitalTime();
    }
  
  //------------------------ First histogram -----------------------------------//
   
   obmin=firstime;
   obmax=lastime;  
  
  oss1.str("");
  oss1 << filename.Data() <<": Physics Packet per minute.  Start time = " << obmin << ", End time = "<< obmax <<" ms";
  Int_t  nbin   = (lastime-firstime)/60000;
  TH1F *h1 = new TH1F ("histo1", oss1.str().c_str(), nbin, obmin, obmax);

  oss2.str("");
  oss2 << filename.Data() <<": Lenght of Physic packets";
  Int_t  nbin2  =(lastime-firstime);
  TH1F *packetLength = new TH1F ("packetLength", oss2.str().c_str(), nbin2, obmin, obmax);

  oss3.str("");
  oss3 << filename.Data() <<": Physics Counter";
  TH1F *packeCounter = new TH1F ("packeCounter", oss3.str().c_str(), nbin2, obmin, obmax);
  //----------------------------------------------------
  TCanvas *finalCanv1 = new TCanvas("Header_1", base, 1280, 1150);
  finalCanv1->Divide(1,3);
  finalCanv1->SetFillColor(10);
  TPad *all2= new TPad ("","", 0, 0, 1, 1);
  all2->SetFillColor(10);
  TPad *all3= new TPad ("","", 0, 0, 1, 1);
  all3->SetFillColor(10);
  TPad *all4= new TPad ("","", 0, 0, 1, 1);
  all4->SetFillColor(10);
  //----------------------------------------------------
  TCanvas *finalCanv2 = new TCanvas("Header_2", base, 1280, 1150);
  finalCanv2->Divide(1,2);
  finalCanv2->SetFillColor(10);

  TMultiGraph *mg1 = new TMultiGraph();
  oss1.str("");
  oss1 << filename.Data() <<": PscuCounter vs FileOffset.";
  mg1->SetTitle(oss1.str().c_str());

  TMultiGraph *mg2 = new TMultiGraph();

  TPad *all= new TPad ("","", 0, 0, 1, 1);
  all->SetFillColor(10);
  TPad *all1= new TPad ("","", 0, 0, 1, 1);
  all1->SetFillColor(10);
  TPad *pad = new TPad("pad","pad", .80,.50,.90,.80);
  pad->SetFillColor(10);
  //--------------------------------------------------------------------------
   for (Int_t l = 0; l < nevents; l++){
    headBr->GetEntry(l);
    ph = eh->GetPscuHeader();  
    h1->Fill(ph->GetOrbitalTime()); 
    packetLength->Fill(ph->GetOrbitalTime(),ph->GetPacketLenght());
    packeCounter->Fill(ph->GetOrbitalTime(),ph->GetCounter());
   }   

  //------------ First Canvas ---------------------//

  finalCanv1->cd(1);
  all2->Draw();
  all2->cd();
  h1->SetStats(kFALSE);
  h1->GetXaxis()->SetTitle("OBT   (ms)");
  h1->GetXaxis()->CenterTitle();
  h1->GetXaxis()->SetLabelSize(0.04);
  h1->GetYaxis()->SetTitle("Number of events ");
  h1->GetYaxis()->CenterTitle();
  h1->GetYaxis()->SetTitleSize(0.06);
  h1->GetYaxis()->SetTitleOffset(0.8);
  h1->Draw();
  

  finalCanv1->cd(2);
  all3->Draw();
  all3->cd();
  packetLength->SetStats(kFALSE);
  packetLength->SetMarkerColor(2);
  packetLength->SetMarkerSize(.5);
  packetLength->SetMarkerStyle(21);
  packetLength->GetXaxis()->SetTitle("OBT    (ms)");
  packetLength->GetXaxis()->CenterTitle();
  packetLength->GetXaxis()->SetLabelSize(0.04);
  packetLength->GetYaxis()->SetTitle("Lenght  (byte)");
  packetLength->GetYaxis()->CenterTitle();
  packetLength->GetYaxis()->SetLabelSize(0.04);
  packetLength->GetYaxis()->SetTitleSize(0.06);
  packetLength->GetYaxis()->SetTitleOffset(0.8);
  packetLength->Draw("9p");

  finalCanv1->cd(3);
  all4->Draw();
  all4->cd();
  packeCounter->SetStats(kFALSE);
  packeCounter->SetMarkerColor(4);
  packeCounter->SetMarkerSize(.5);
  packeCounter->SetMarkerStyle(21);
  packeCounter->GetXaxis()->SetTitle("OBT    (ms)");
  packeCounter->GetXaxis()->SetTitleSize(0.05);
  packeCounter->GetXaxis()->CenterTitle();
  packeCounter->GetXaxis()->SetLabelSize(0.04);
  packeCounter->GetYaxis()->SetTitle("Counter");
  packeCounter->GetYaxis()->SetTitleSize(0.05);
  packeCounter->GetYaxis()->CenterTitle();
  packeCounter->GetYaxis()->SetLabelSize(0.04);
  packeCounter->GetYaxis()->SetTitleSize(0.06);
  packeCounter->GetYaxis()->SetTitleOffset(0.8);
  Double_t min = 500000000.;
   for (Int_t l = 0; l < nevents; l++){
     if((packeCounter->GetBinContent(l))<=  min && (packeCounter->GetBinContent(l))!= 0) min = packeCounter->GetBinContent(l);
   }   
  packeCounter->SetMinimum(min);
  packeCounter->Draw("9p");
  
  oss.str("");
  oss << outDir.Data() << filename.Data();
  oss  << "_HeaderScan_1." << format.Data();
  finalCanv1->SaveAs(oss.str().c_str());
  
  //-------------------------------------------------
  TList *list = new TList;
  Int_t numkey;
  TObject *key = new TObject;
  const char *name;
  TTree* tr = new TTree;
  Long64_t nevntskey=0;
  list = file->GetListOfKeys(); 
  numkey = file->GetNkeys();

  const Int_t size1 = 10000;
  Int_t ev1=0;
  Double_t PscuCounter1[size1], FileOffset1[size1], tempo1[size1], salto[size1];
  Int_t pag1=0;
  Int_t m1=0;
  Int_t ll=0;

  for (Int_t i=0; i<numkey; i++){
    key = list->At(i);
    name=(char *)(key->GetName());
    tr = (TTree*)file->Get(name);
    if (tr->IsZombie()) continue;
    tr->SetBranchAddress("Header", &eh);
    TBranch *Br = tr->GetBranch("Header");
    nevntskey = tr->GetEntries();
    m1=0;
    pag1= (nevntskey/10000)+1;
 /////ciclo sulle pagine////////////////////
  for (Int_t interval1=0; interval1<pag1; interval1++){

   for (Int_t l = 0; l < size1; l++){     //ciclo su un sottogruppo
    Br->GetEntry(ev1+l);
    ph = eh->GetPscuHeader();  
    PscuCounter1[l]= ph->GetCounter(); // = PcktCounter[l]
    FileOffset1[l]=ph->GetFileOffset();
    tempo1[l]=ph->GetOrbitalTime();
    if(ph->GetFileOffset()<= primoffset){
      primoffset =ph->GetFileOffset();
      primotempo=ph->GetOrbitalTime();
    }
    if(ph->GetFileOffset()>= ultimoffset){
      ultimoffset = ph->GetFileOffset();
      ultimotempo = ph->GetOrbitalTime();
    }
    if(l>0){
      if(tempo1[l] < tempo1[l-1]){
	salto[ll]= ph->GetOrbitalTime();
	ll=ll+1;
	  }
    }
    
    m1=l;
   }  

   TGraph *graph3= new TGraph(m1, FileOffset1, PscuCounter1);
   graph3->SetMarkerColor(3);
   graph3->SetMarkerSize(.5);
   graph3->SetMarkerStyle(21);
   mg1->Add(graph3);

   TGraph *graph4= new TGraph(m1, FileOffset1, tempo1);
   graph4->SetMarkerColor(kBlue);
   graph4->SetMarkerSize(.5);
   graph4->SetMarkerStyle(21);
   mg2->Add(graph4);

   ev1=ev1+10000;
  }
  }

  
    TLatex *lat = new TLatex();
    lat->SetTextAlign(12);
    lat->SetTextSize(0.15);
    lat->SetTextColor(kBlue);
  

  //------------ Second Canvas ---------------------//
   finalCanv2->cd(1);
   all1->Draw();
   all1->cd();
   mg1->Draw("AP");
   mg1->GetXaxis()->SetTitle("File Offset");
   mg1->GetXaxis()->CenterTitle();
   mg1->GetXaxis()->SetTitleSize(0.05);
   mg1->GetXaxis()->SetLabelSize(0.04);
   mg1->GetYaxis()->SetTitle("Counter");
   mg1->GetYaxis()->CenterTitle();
   mg1->GetYaxis()->SetTitleSize(0.05);
   mg1->GetYaxis()->SetLabelSize(0.03);

   finalCanv2->cd(2);
   all->Draw();
   all->cd();
   
   oss3.str("");
   oss3 << filename.Data() <<" OBT vs FileOffset.  First packet = "<<primotempo <<" ms,  Last packet = "<<ultimotempo<<" ms.";
   mg2->SetTitle(oss3.str().c_str());
   mg2->Draw("AP");
   mg2->GetXaxis()->SetTitle("File Offset");
   mg2->GetXaxis()->CenterTitle();
   mg2->GetXaxis()->SetTitleSize(0.05);
   mg2->GetXaxis()->SetLabelSize(0.04);
   mg2->GetYaxis()->SetTitle("OBT");
   mg2->GetYaxis()->CenterTitle();
   mg2->GetYaxis()->SetTitleSize(0.05);
   mg2->GetYaxis()->SetLabelSize(0.03);
   double min2 = 0.8;
   if(ll-1 > 0){
   pad->Draw();
   pad->cd();
    stringa.str("");
    stringa << "jump back at:";
    lat->DrawLatex(0.08, min2, stringa.str().c_str()); 
    for(Int_t kk=0; kk <(ll-1); kk++){
      stringa.str("");
      stringa << salto[kk];
      min2=min2-0.1;
      lat->DrawLatex(0.08, min2,stringa.str().c_str()); 
      //cout<<salto[kk]<<";\n";
    }
  }

   finalCanv2->Update();





   oss1.str("");
   oss1 << outDir.Data() << filename.Data();
   oss1 << "_HeaderScan_2"<<"." << format.Data();

   finalCanv2->SaveAs(oss1.str().c_str());
  
   file->Close();
  
}

int main(int argc, char* argv[]){
  TString path;
  TString outDir     = "./";
  TString format     = "jpg";
 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: HeaderScan 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[jpg|ps|gif]    Format for output files [default 'jpg'] \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;
      }
    }
  }
  HeaderScan(argv[1], outDir, format);
}
