/**
* 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 
*
* Version 1.9
* Date 7 March 2007 - Malvezzi
*
* Description: to read correctly the OBT changed the type of time variables from signed to unsigned 
*
*/


#include <fstream>
#include <math.h>
#include "TLatex.h"
#include "TF1.h"
#include "TPaveText.h"
#include "TMultiGraph.h"
#include <sstream>
#include <iostream>
#include <stdio.h>
#include <string.h>
#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"
#include "RunHeaderEvent.h"
#include "TPaveText.h"

using namespace std;

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

  //------------------- Variables initilization -------------------------//
  Long64_t nevents=0, runnevents; 
  ULong_t lastime, firstime, primotempo, ultimotempo, primoffset=500000000, ultimoffset;
  double obmin=0.;
  double obmax=0.; 
  stringstream oss, oss1, oss2, oss3, noentries, stringa;

  //-------------- Load root file, tree and branch  -------------------//
  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   = new pamela::EventHeader;
  pamela::PscuHeader   *ph   = new pamela::PscuHeader;

  PhysicsTr->SetBranchAddress("Header", &eh);
  nevents = PhysicsTr->GetEntries();
  const Int_t size = nevents;

  TTree *RunHeadTr = (TTree*)file->Get("RunHeader");  ///run header tree
  pamela::EventHeader *eH= new pamela::EventHeader;
  pamela::RunHeaderEvent *reh=new pamela::RunHeaderEvent;
  
  RunHeadTr->SetBranchAddress("Header",&eH);
  RunHeadTr->SetBranchAddress("RunHeader",&reh);
  runnevents = RunHeadTr->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();
   headBr->GetEntry(nevents);
   ph = eh->GetPscuHeader();
   lastime = ph->GetOrbitalTime();
   int i =0;
   while(i < nevents){
     headBr->GetEntry(i);
     ph = eh->GetPscuHeader();
     if((ph->GetOrbitalTime()) <= firstime) firstime=ph->GetOrbitalTime();
     if((ph->GetOrbitalTime()) >= lastime) lastime=ph->GetOrbitalTime();
     i++;
     }
  
  //------------------------ First histogram -----------------------------------//
  obmin=firstime;
  obmax=lastime; 
  Int_t  nbin   = (lastime-firstime)/60000;
  TH1F *h1 = new TH1F ("histo1", "" , nbin, obmin, obmax);

  //------------------- fill vectors and histogram -----------------------------//
  Double_t *PscuCounter = new Double_t[size];
  Double_t *PacketLenght = new Double_t[size];
  ULong_t utile=0;
  double *OBTime = new Double_t[size];
  Double_t *Eventsperminute= new Double_t[nbin];
  Double_t *Minute= new Double_t[nbin];
  Double_t max=0;
  for (Int_t k = 0; k < nevents; k++){
    headBr->GetEntry(k);
    ph = eh->GetPscuHeader(); 
    utile= ph->GetOrbitalTime();
    h1->Fill(utile); 
    PscuCounter[k]= ph->GetCounter();
    PacketLenght[k]=ph->GetPacketLenght();
    OBTime[k]=utile;
  }   
  int l=0;
  while(l<nbin){
    Eventsperminute[l]=h1->GetBinContent(l);
    Minute[l]=firstime+l*60000;
    if(h1->GetBinContent(l) >= max)max =h1->GetBinContent(l);
    l++;
  }

  //----------- Graph and MultiGraph -----------------------------------------------//
  TMultiGraph *rate = new TMultiGraph();
  TMultiGraph *packetLength = new TMultiGraph();
  TMultiGraph *packeCounter = new TMultiGraph();

  oss1.str("");
  oss1 << "Physics Packet per minute.  Start time = " << obmin << ", End time = "<< obmax <<" ms";
  TGraph *rate1= new TGraph(nbin, (const Double_t*)Minute, (const Double_t*)Eventsperminute);
  rate1->SetMarkerColor(kBlack);
  rate1->SetMarkerSize(.1);
  rate1->SetMarkerStyle(21);
  rate->Add(rate1);

  TGraph *packetLength1= new TGraph(nevents, (const double*)OBTime, (const double*)PacketLenght);
  oss2.str("");
  oss2 <<"Lenght of Physic packets";
  packetLength1->SetMarkerColor(2);
  packetLength1->SetMarkerSize(.3);
  packetLength1->SetMarkerStyle(21);
  packetLength->Add(packetLength1);

  TGraph *packeCounter1= new TGraph(nevents, (const Double_t*)OBTime, (const Double_t*)PscuCounter);
  oss3.str("");
  oss3 <<"Physics Counter vs. OBT";
  packeCounter1->SetMarkerColor(4);
  packeCounter1->SetMarkerSize(.2);
  packeCounter1->SetMarkerStyle(21);
  packeCounter->Add(packeCounter1);

  //------------ Create and Draw Canvas ---------------------//
  TCanvas *finalCanv = new TCanvas("Header", base, 1200, 1600);
  finalCanv->Divide(1,6);
  finalCanv->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);
  TPad *all= new TPad ("","", 0, 0, 1, 1);
  all->SetFillColor(10);
  TPad *all1= new TPad ("","", 0, 0, 1, 1);
  all1->SetFillColor(10);

  TLine li;
  li.SetLineStyle(4);
  li.SetLineWidth(2);

  //----------- First PAD -------------------------------//
  finalCanv->cd(1);
  all2->Draw();
  all2->cd();
  rate->Draw("ALP");
  rate->GetXaxis()->SetTitle("OBT   (ms)");
  rate->GetXaxis()->SetTitleSize(0.05);
  rate->GetXaxis()->CenterTitle();
  rate->GetXaxis()->SetLabelSize(0.05);
  rate->GetYaxis()->SetTitle("Number of events ");
  rate->GetYaxis()->CenterTitle();
  rate->GetYaxis()->SetLabelSize(0.05);
  rate->GetYaxis()->SetTitleSize(0.06);
  rate->GetYaxis()->SetTitleOffset(0.6);
  for (Int_t l = 0; l < runnevents; l++){
    RunHeadTr->GetEntry(l);
    ph = eH->GetPscuHeader();
    int ws= reh->RM_ACQ_SETTING_MODE;
    int id = ph->GetPacketId1();
    ULong_t utile1=ph->GetOrbitalTime();
    Double_t obt = utile1;
    if (ws==1){
      li.SetLineColor(3);
      li.DrawLine(obt,0,obt,max);
    }
    else if (ws==2){
      li.SetLineColor(4);
      li.DrawLine(obt,0,obt,max);
    }  
  }
  
  RunHeadTr->GetEntry(0);
  ph = eH->GetPscuHeader();
  ULong_t TimeSync = reh->LAST_TIME_SYNC_INFO; 
  ULong_t ObtSync = reh->OBT_TIME_SYNC; 
  //cout<<"TimeSync "<<reh->LAST_TIME_SYNC_INFO<<"\n";
  //cout<<"ObtSync "<<reh->OBT_TIME_SYNC<<"\n";

  finalCanv->cd(1);
  stringstream ws1, ws2;
  ws1.str("");
  ws2.str("");
  ws1<<"ACQ_SETTING_MODE = 1";
  ws2<<"ACQ_SETTING_MODE = 2";
  TPaveText *pt=0;
  pt = new TPaveText (.60,.92,.76,.98);
  pt->AddText(ws1.str().c_str());
  pt->SetTextColor(3);
  pt->SetFillColor(10);
  pt->SetBorderSize(0);
  pt->Draw();
  TPaveText *pt1=0;
  pt1 = new TPaveText (.76,.92,.92,.98);
  pt1->AddText(ws2.str().c_str());
  pt1->SetTextColor(4);
  pt1->SetFillColor(10);
  pt1->SetBorderSize(0);
  pt1->Draw();
  pt1 = new TPaveText (.05,.91,.6,1);
  pt1->AddText(oss1.str().c_str());
  pt1->SetTextColor(1);
  pt1->SetFillColor(10);
  pt1->SetBorderSize(0);
  pt1->Draw();

  //----------- Second PAD -------------------------------//
  finalCanv->cd(2);
  all3->Draw();
  all3->cd();
  packetLength->Draw("AP");
  packetLength->GetXaxis()->SetTitle("OBT    (ms)");
  packetLength->GetXaxis()->SetTitleSize(0.05);
  packetLength->GetXaxis()->CenterTitle();
  packetLength->GetXaxis()->SetLabelSize(0.05);
  packetLength->GetYaxis()->SetTitle("Lenght  (byte)");
  packetLength->GetYaxis()->CenterTitle();
  packetLength->GetYaxis()->SetLabelSize(0.05);
  packetLength->GetYaxis()->SetTitleSize(0.06);
  packetLength->GetYaxis()->SetTitleOffset(0.6);


  finalCanv->cd(2);
  pt = new TPaveText (.6,.91,.90,1);
  pt->AddText(oss2.str().c_str());
  pt->SetTextColor(2);
  pt->SetFillColor(10);
  pt->SetBorderSize(0);
  pt->Draw();

  //----------- Third PAD -------------------------------//
  finalCanv->cd(3);
  all4->Draw();
  all4->cd();
  packeCounter->Draw("AP");
  packeCounter->GetXaxis()->SetTitle("OBT    (ms)");
  packeCounter->GetXaxis()->SetTitleSize(0.05);
  packeCounter->GetXaxis()->CenterTitle();
  packeCounter->GetXaxis()->SetLabelSize(0.05);
  packeCounter->GetYaxis()->SetTitle("Counter");
  packeCounter->GetYaxis()->SetTitleSize(0.05);
  packeCounter->GetYaxis()->CenterTitle();
  packeCounter->GetYaxis()->SetLabelSize(0.05);
  packeCounter->GetYaxis()->SetTitleSize(0.06);
  packeCounter->GetYaxis()->SetTitleOffset(0.6);


  finalCanv->cd(3);
  TPaveText *pt2=0;
  pt2 = new TPaveText (.6,.91,.90,1);
  pt2->AddText(oss3.str().c_str());
  pt2->SetTextColor(4);
  pt2->SetFillColor(10);
  pt2->SetBorderSize(0);
  pt2->Draw();  
 
  /**********************************************************************************************/

  TMultiGraph *mg1 = new TMultiGraph();
  TMultiGraph *mg2 = new TMultiGraph();
  //---------------------- fill vectors and histogram --------------------------------------------------//
  TList *list = new TList;
  Int_t numkey;
  TObject *key = new TObject;
  const char *name;
  char *SoftInfo="SoftInfo";
  TTree* tr = new TTree;
  Long64_t nevntskey=0;
  list = file->GetListOfKeys(); 
  numkey = file->GetNkeys();
  ULong_t salto;
  for (Int_t m=0; m<numkey; m++){
    key = list->At(m);
    name=(char *)(key->GetName());
    if(strcmp(name,SoftInfo)==0)continue;
    tr = (TTree*)file->Get(name);
    if (tr->IsZombie()) continue;

    tr->SetBranchAddress("Header", &eh);
    TBranch *Br = tr->GetBranch("Header");
    nevntskey = tr->GetEntries();
    if(nevntskey !=0){
      Int_t size1=nevntskey;
      Double_t *PscuCounter1 = new Double_t[size1];
      Double_t *FileOffset1 = new Double_t[size1];
      Double_t *tempo1 = new Double_t[size1];

      int n=0;
      while(n<nevntskey){
	Br->GetEntry(n);
	ph = eh->GetPscuHeader();  
	PscuCounter1[n]= ph->GetCounter();
	FileOffset1[n]=ph->GetFileOffset();
	utile=ph->GetOrbitalTime();
	tempo1[n]=utile;
	if((m==0) && (n==0)){
	  primotempo=ph->GetOrbitalTime();
	  salto=ph->GetOrbitalTime();
	}
	if(salto > ph->GetOrbitalTime())salto=ph->GetOrbitalTime();
	if(ph->GetFileOffset()<= primoffset){
	  primoffset=ph->GetFileOffset();
	  primotempo=ph->GetOrbitalTime();
	}
	if(ph->GetFileOffset()>=ultimoffset){
	  ultimotempo=ph->GetOrbitalTime();
	  ultimoffset=ph->GetFileOffset();
	}
	n++;
      }

      TGraph *graph3= new TGraph(nevntskey, (const Double_t*)FileOffset1, (const Double_t*)PscuCounter1);
      graph3->SetMarkerColor(3);
      graph3->SetMarkerSize(.2);
      graph3->SetMarkerStyle(21);
      mg1->Add(graph3);
      
      TGraph *graph4= new TGraph(nevntskey, (const Double_t*)FileOffset1, (const Double_t*)tempo1);
      graph4->SetMarkerColor(kBlue);
      graph4->SetMarkerSize(.2);
      graph4->SetMarkerStyle(21);
      mg2->Add(graph4);
    }
  }

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

 //------------ Fourth PAD  ---------------------//
   finalCanv->cd(4);
   all1->Draw();
   all1->cd();

   oss1.str("");
   oss1 <<"PscuCounter vs FileOffset.";
   mg1->Draw("AP");
   mg1->GetXaxis()->SetTitle("File Offset");
   mg1->GetXaxis()->CenterTitle();
   mg1->GetXaxis()->SetTitleOffset(0.8);
   mg1->GetXaxis()->SetTitleSize(0.05);
   mg1->GetXaxis()->SetLabelSize(0.05);
   mg1->GetYaxis()->SetTitle("Counter");
   mg1->GetYaxis()->CenterTitle();
   mg1->GetYaxis()->SetTitleSize(0.06);
   mg1->GetYaxis()->SetLabelSize(0.06);
   mg1->GetYaxis()->SetTitleOffset(0.6);
   finalCanv->cd(4);
   TPaveText *pt3=0;
   pt3 = new TPaveText (.60,.91,.90,1);
   pt3->AddText(oss1.str().c_str());
   pt3->SetTextColor(3);
   pt3->SetFillColor(10);
   pt3->SetBorderSize(0);
   pt3->Draw();

 //------------ Fifth PAD  ---------------------//
   finalCanv->cd(5);
   all->Draw();
   all->cd();
   oss3.str("");
   oss3 << "OBT vs FileOffset";
   mg2->Draw("AP");
   mg2->GetXaxis()->SetTitle("File Offset");
   mg2->GetXaxis()->CenterTitle();
   mg2->GetXaxis()->SetTitleSize(0.05);
   mg2->GetXaxis()->SetLabelSize(0.05);
   mg2->GetYaxis()->SetTitle("OBT");
   mg2->GetYaxis()->CenterTitle();
   mg2->GetYaxis()->SetTitleSize(0.06);
   mg2->GetYaxis()->SetLabelSize(0.05);
   mg2->GetYaxis()->SetTitleOffset(0.6);

   finalCanv->cd(5);
   TPaveText *pt4=0;
   pt4 = new TPaveText (.70,.91,.90,1);
   pt4->AddText(oss3.str().c_str());
   pt4->SetTextColor(kBlue);
   pt4->SetFillColor(10);
   pt4->SetBorderSize(0);
   pt4->Draw();

   finalCanv->cd(6);
   ULong_t primotempoABS=TimeSync+((primotempo/1000)-ObtSync);
   ULong_t obmaxABS=TimeSync+((lastime/1000)-ObtSync);
   ULong_t saltoABS=TimeSync+((salto/1000)-ObtSync);
   ULong_t ultimotempoABS=TimeSync+((ultimotempo/1000)-ObtSync);

   TPaveText *pt5=0;
   pt5 = new TPaveText (0,0,1,1);
   stringa.str("");
   stringa << "  Filename:   "<<filename.Data()<<"\n";
   TText *t1=pt5->AddText(0.25,0.95,stringa.str().c_str());
   t1->SetTextSize(0.1);
   stringa.str("");
   stringa << "  OBT (ms)            ABS TIME (s)";
   TText *t2=pt5->AddText(0.32,0.75,stringa.str().c_str());
   t2->SetTextSize(0.07);
   stringa.str("");
   stringa << "New data start at:   "<<primotempo<<"         "<<primotempoABS;
   TText *t3=pt5->AddText(0.25,0.60,stringa.str().c_str());
   t3->SetTextSize(0.08);
   stringa.str("");
   stringa << "New data end at:     "<<lastime<<"         "<<obmaxABS;
   TText *t4=pt5->AddText(0.25,0.50,stringa.str().c_str());
   t4->SetTextSize(0.08);
   if(primotempo!=salto || lastime!=ultimotempo){
     stringa.str("");
     stringa << "Old data start at:   "<<salto<<"        "<<saltoABS;
     TText *t5=pt5->AddText(0.65,0.60,stringa.str().c_str());
     t5->SetTextSize(0.08);
     stringa.str("");
     stringa << "Old data end at:     "<<ultimotempo<<"        "<<ultimotempoABS;
     TText *t6=pt5->AddText(0.65,0.50,stringa.str().c_str());
     t6->SetTextSize(0.08);
     stringa.str("");
     stringa << "  OBT (ms)          ABS TIME (s)";
     TText *t2=pt5->AddText(0.72,0.75,stringa.str().c_str());
     t2->SetTextSize(0.07);
   }
   pt5->SetTextColor(kBlack);
   pt5->SetFillColor(10);
   pt5->SetBorderSize(0);
   pt5->Draw();

   finalCanv->Update();

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

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

