/**
* 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.
*
*/


#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,obt;
  double obmin=0.;
  double obmax=0.; 
  Float_t maxoffset, minoffset;
  stringstream oss, oss1, oss2, oss3, noentries;
  //------- 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 ----------------------------//
  for (Int_t i = 0; i < nevents; i++){
    headBr->GetEntry(i);
    ph = eh->GetPscuHeader();
    obt = ph->GetOrbitalTime();
    if(obt <= firstime) firstime=obt;
    if(obt >= lastime) lastime=obt;
    }
  //*************************** Histograms ************************************************************//
  //------------------------ First histogram -----------------------------------//
  obmin=firstime;
  obmax=lastime;  
  oss1.str("");
  oss1 <<"File name= "<< filename.Data() <<". Start time= " << obmin << ", end time= "<< obmax <<" ms"<<". Physics Packet per minute";
  Int_t  nbin   = (lastime-firstime)/60000;
  TH1F *h1 = new TH1F ("histo1", oss1.str().c_str(), nbin, obmin, obmax);
 
  //------------------------ Second histogram -----------------------------------//
  oss2.str("");
  oss2 << " Lenght of Physic packets;";
  Int_t nint = (lastime-firstime);
  TH1F *PcktLenght = new TH1F ("histo2", oss2.str().c_str(), nint, obmin, obmax);

 //------------------------ Third histogram -----------------------------------//
  oss3.str("");
  oss3 << " Physics Counter";
  TH1F *PcktCounter = new TH1F ("histo3", oss3.str().c_str(), nint, obmin, obmax);

  //**************************************************************************************************//
  //------- fill histograms ---------//

  for (Int_t i = 0; i < nevents; i++){
    headBr->GetEntry(i);
    ph = eh->GetPscuHeader();  
    h1->Fill(ph->GetOrbitalTime());  
    PcktLenght->Fill(ph->GetOrbitalTime(),ph->GetPacketLenght());  
    PcktCounter->Fill(ph->GetOrbitalTime(),ph->GetCounter());
  }

  //****************************** Canvases *******************************//
  //TGaxis::SetMaxDigits(4);
  //------------------- First Canvas --------------------------------//
  TCanvas *finalCanv1 = new TCanvas("Header_1", base, 1280, 1024);
  finalCanv1->Divide(1,3);
  finalCanv1->SetFillColor(10);

  finalCanv1->cd(1);
  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);
  PcktLenght->SetStats(kFALSE);
  PcktLenght->GetXaxis()->SetTitle("OBT    (ms)");
  PcktLenght->GetXaxis()->CenterTitle();
  PcktLenght->GetXaxis()->SetLabelSize(0.04);
  PcktLenght->GetYaxis()->SetTitle("Lenght  (byte)");
  PcktLenght->GetYaxis()->CenterTitle();
  PcktLenght->GetYaxis()->SetLabelSize(0.04);
  PcktLenght->GetYaxis()->SetTitleSize(0.06);
  PcktLenght->GetYaxis()->SetTitleOffset(0.8);
  PcktLenght->SetMarkerColor(2);
  PcktLenght->SetMarkerSize(.5);
  PcktLenght->SetMarkerStyle(21);
  PcktLenght->Draw("9p");

  finalCanv1->cd(3);
  PcktCounter->SetStats(kFALSE);
  PcktCounter->GetXaxis()->SetTitle("OBT    (ms)");
  PcktCounter->GetXaxis()->SetTitleSize(0.05);
  PcktCounter->GetXaxis()->CenterTitle();
  PcktCounter->GetXaxis()->SetLabelSize(0.04);
  PcktCounter->GetYaxis()->SetTitle("Counter");
  PcktCounter->GetYaxis()->SetTitleSize(0.05);
  PcktCounter->GetYaxis()->CenterTitle();
  PcktCounter->GetYaxis()->SetLabelSize(0.04);
  PcktCounter->GetYaxis()->SetTitleSize(0.06);
  PcktCounter->GetYaxis()->SetTitleOffset(0.8);
  PcktCounter->SetMarkerColor(4);
  PcktCounter->SetMarkerSize(.5);
  PcktCounter->SetMarkerStyle(21);
  PcktCounter->Draw("9p");

  oss.str("");
  oss << outDir.Data() << filename.Data();
  oss  << "_HeaderScan_1." << format.Data();
  finalCanv1->SaveAs(oss.str().c_str());
  //------------- Graph PscuCounter vs FileOffset ---------------------------------
  const Int_t size = 100000;
  Int_t ev=0;
  Double_t PscuCounter[size], FileOffset[size];
  Int_t m=0;
  Int_t pag= (nevents/100000)+1;

  TCanvas *finalCanv2 = new TCanvas("Header_2", base, 1280, 1024);
  finalCanv2->SetFillColor(10);

 /////ciclo sulle pagine////////////////////
  for (Int_t interval=0; interval<pag; interval++){

   for (Int_t l = 0; l < size; l++){     //ciclo su un sottogruppo
    headBr->GetEntry(ev+l);
    ph = eh->GetPscuHeader();  
    PscuCounter[l]= ph->GetCounter();
    FileOffset[l]=ph->GetFileOffset();
    m=l;
   }   

   oss1.str("");
   oss1 << filename.Data() <<": PscuCounter vs FileOffset. Canvas n."<< (interval+1);
   TGraph *graph= new TGraph(m, FileOffset, PscuCounter);

   finalCanv2->cd();
   graph->SetTitle(oss1.str().c_str());
   graph->GetXaxis()->SetTitle("File Offset");
   graph->GetXaxis()->CenterTitle();
   graph->GetXaxis()->SetTitleSize(0.04);
   graph->GetXaxis()->SetLabelSize(0.02);
   graph->GetYaxis()->SetTitle("Counter");
   graph->GetYaxis()->CenterTitle();
   graph->GetYaxis()->SetTitleSize(0.04);
   graph->GetYaxis()->SetLabelSize(0.02);
   graph->SetMarkerColor(3);
   graph->SetMarkerSize(.5);
   graph->SetMarkerStyle(21);
   graph->Draw("AP");

   oss1.str("");
   oss1 << outDir.Data() << filename.Data();
   oss1 << "_HeaderScan_2_"<<(interval+1)<<"." << format.Data();

   finalCanv2->SaveAs(oss1.str().c_str());
   finalCanv2->Clear();

   ev=ev+100000;
  }

  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);
}
