//
//   Shows calorimeter tracks - Emiliano Mocchiutti
//
//   FCaloMATRA.cxx    version 1.01 (2006-03-07)
//
//   The only input needed is the path to the directory created by YODA for the data file you want to analyze.
//
//   Changelog:
//
//   1.00 - 1.01 (2006-03-07): Flight version, read unique YODA file.  
//
//   0.00 - 1.00 (2006-03-07): Clone of CaloMATARA v3r00.
//
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <fstream>
#include <sstream>
#include <TTree.h>
#include <TObjectTable.h>
#include <TClassEdit.h>
#include <TObject.h>
#include <TList.h>
#include <TSystem.h>
#include <TSystemDirectory.h>
#include <TString.h>
#include <TFile.h>
#include <TClass.h>
#include <TCanvas.h>
#include <TH1.h>
#include <TH1F.h>
#include <TH2D.h>
#include <TLatex.h>
#include <TPad.h>
#include <TPaveLabel.h>
#include <TChain.h>
#include <TApplication.h>
#include <TStyle.h>
extern bool existfile(TString);
extern void stringcopy(TString&, const TString&, Int_t, Int_t);
extern void ColorMIP(Float_t, int&);
extern Int_t WhatToDo(int&, int&, int&, Long64_t, Float_t, Float_t, const char*, TString, TString, TCanvas&);
extern TString getFilename(const TString);
extern void *processevents(void *);
//
#include <caloclassesfun.h>
//
using namespace std;


void FCaloMATRA(TString filename, Int_t fromevent = 1, Int_t toevent = 0, TString tyhist="box", TString outDir = "", TString saveas = "gif"){
  Int_t doflag = 1;
  TApplication *app;
  if ( !gROOT->GetListOfClasses()->FindObject("TRint") ){
    //
    app = new TApplication("app",0,0);
  };
  const char* startingdir = gSystem->WorkingDirectory();
  if ( !strcmp(outDir.Data(),"") ) outDir = startingdir;
  if ( !existfile(filename) ){
    printf(" %s :no such file or directory \n",filename.Data());
    printf("\n ERROR: No calorimeter LEVEL1 file! \n\n Run FCaloLEVEL1 to generate level1 data. \n\n");	
    return;
  };
  //
  TFile *File = new TFile(filename.Data());
  TTree *otr = (TTree*)File->Get("CaloLevel1");
  if ( !otr ){
    printf(" %s are you sure? I need a LEVEL1 file! \n",filename.Data());
    return;
  };
  //    
  CalorimeterLevel1 *calo = new CalorimeterLevel1();
  otr->SetBranchAddress("Event", &calo);
  //    
  Long64_t nevents    = otr->GetEntries();
  stringstream titolo;
  stringstream stringa;
  TString fififile =  getFilename(filename);
  const char *file = fififile;
  //    
  //
  // input limits
  //
  if ( tyhist != "box" && tyhist != "lego" ) {
    printf("You can choose tyhist as box (default) or lego \n");
    return;
  };

  if ( fromevent > toevent && toevent ){
    printf("It must be fromevent < toevent \n");
    return;
  };


  if ( fromevent > nevents+1 || fromevent < 0 ) {
    printf("You can choose fromevent between 0 (all) and %i \n",(int)nevents+1);
    return;
  };

  if ( toevent > nevents+1 || toevent < 0 ) {
    printf("You can choose toevent between 0 (all) and %i \n",(int)nevents+1);
    return;
  };
  Int_t minevent = 0;
  Int_t maxevent = nevents;
  if ( fromevent == 0 ) {
    minevent = 0;
    maxevent = nevents;
  } else {
    minevent = fromevent - 1;
    if ( toevent > 0 ){
      maxevent = toevent - 1;
    } else {
      maxevent = fromevent -1;
    };
  };

  //
  // run over all the events
  //
  TCanvas *figura2 = new TCanvas("Calorimeter_tracks", "Calorimeter_tracks", 750, 650);
  figura2->SetFillColor(10);
  figura2->Range(0,0,100,100);
  Int_t i = minevent;
  while ( i < maxevent+1 ){
    figura2->Clear();
    //
    // variables definition
    //
    Int_t badstrip = 0;
    //
    // Book the histograms:
    //
    //
    stringstream xview;
    xview.str("");
    xview << "x-view event " << (i+1);
    stringstream yview;
    yview.str("");
    yview << "y-view event " << (i+1);
    gDirectory->Delete(xview.str().c_str());
    gDirectory->Delete(yview.str().c_str());
    TH2F *Xview = new TH2F(xview.str().c_str(),"",96,-0.5,95.5,22,-0.5,21.5);
    TH2F *Yview = new TH2F(yview.str().c_str(),"",96,-0.5,95.5,22,-0.5,21.5);	
    //
    // figures:
    //
    Int_t bgcolor = 10;
    TLatex *t=new TLatex();
    t->SetTextFont(32);
    t->SetTextColor(1);
    t->SetTextSize(0.03);
    t->SetTextAlign(12);
    titolo.str("");
    titolo << "Calorimeter tracks - file " << file;
    titolo << " - event number " << (i+1);
    t->DrawLatex(0.5,97.,titolo.str().c_str());
    Float_t paddim = 0.88;
    if ( !strcmp(tyhist.Data(),"lego") ){
      paddim = 0.98;
    } else {
      paddim = 0.88;
    };
    TPad *pd1 = new TPad("pd1","This is pad1",0.02,0.05,paddim,0.49,bgcolor);
    TPad *pd2 = new TPad("pd2","This is pad2",0.02,0.51,paddim,0.95,bgcolor);
    TPad *palette = 0;
    figura2->cd();
    pd1->Range(0,0,100,100);
    pd2->Range(0,0,100,100);
    pd1->SetTicks();
    pd2->SetTicks();
    pd1->Draw();
    pd2->Draw();
    if ( !strcmp(tyhist.Data(),"box") ){
      palette = new TPad("palette","This is palette",0.90,0.05,0.98,0.9,bgcolor);
      figura2->cd();
      t=new TLatex();
      t->SetTextFont(32);
      t->SetTextColor(1);
      t->SetTextSize(0.03);
      t->SetTextAlign(12);
      t->DrawLatex(92.,92.5,"MIP");
      palette->Range(0,0,100,100);
      palette->Draw();
      palette->cd();
      // palette
      TPaveLabel *box1 = new TPaveLabel(2,2,98,16.3,"0","");
      box1->SetTextFont(32);
      box1->SetTextColor(1);	
      box1->SetTextSize(0.25);	
      box1->SetFillColor(10);
      box1->Draw();
      TPaveLabel *box2 = new TPaveLabel(2,18.3,98,32.66,"0-2","");
      box2->SetTextFont(32);
      box2->SetTextColor(1);		
      box2->SetTextSize(0.25);	
      box2->SetFillColor(38);
      box2->Draw();
      TPaveLabel *box3 = new TPaveLabel(2,34.66,98,48.96,"2-10","");
      box3->SetTextFont(32);
      box3->SetTextColor(1);	
      box3->SetTextSize(0.25);	
      box3->SetFillColor(4);
      box3->Draw();
      TPaveLabel *box4 = new TPaveLabel(2,50.96,98,65.26,"10-100","");
      box4->SetTextFont(32);
      box4->SetTextColor(1);	
      box4->SetTextSize(0.25);	
      box4->SetFillColor(3);
      box4->Draw();
      TPaveLabel *box5 = new TPaveLabel(2,67.26,98,81.56,"100-500","");
      box5->SetTextFont(32);
      box5->SetTextColor(1);	
      box5->SetTextSize(0.2);	
      box5->SetFillColor(2);
      box5->Draw();
      TPaveLabel *box6 = new TPaveLabel(2,83.56,98,97.86,">500","");
      box6->SetTextFont(32);
      box6->SetTextColor(1);	
      box6->SetTextSize(0.25);	
      box6->SetFillColor(6);
      box6->Draw();
    };
    figura2->cd();
    gStyle->SetOptDate(1);
    if ( tyhist == "box" ) {
      pd1->cd();	   
      gStyle->SetOptStat(0);
      Xview->SetXTitle("strip");
      Xview->SetYTitle("X - plane");
      Xview->GetYaxis()->SetTitleOffset(0.5);
      Xview->SetFillColor(bgcolor);	    
      Xview->Fill(1.,1.,1.);	    
      Xview->Draw(tyhist);
      pd1->Update();
      pd2->cd();
      gStyle->SetOptStat(0);
      Yview->SetXTitle("strip");
      Yview->SetYTitle("Y - plane");
      Yview->GetYaxis()->SetTitleOffset(0.5);	
      Yview->SetFillColor(bgcolor);	    
      Yview->Fill(1.,1.,1.);	    
      Yview->Draw(tyhist);
      pd2->Update();
    };
    //
    // read from the header of the event the absolute time at which it was recorded
    //
    otr->GetEntry(i);
    //
    // run over views and planes
    //
    for (Int_t m = 0; m < 22; m++){
      for (Int_t l = 0; l < 2; l++){
	for (Int_t n = 0; n < 96; n++){
	  if ( calo->estrip[l][m][n] > 0.7 ) {
	    //
	    // OK, now in estrip we have the energy deposit in MIP of all the strips for this event (at the end of loops of course)
	    //			
	    if ( tyhist == "box" ){
	      xview.str("");
	      xview << "x-view event " << n;
	      xview << " " << m;
	      xview << " " << l;
	      yview.str("");
	      yview << "y-view event " << n;
	      yview << " " << m;
	      yview << " " << l;
	      gDirectory->Delete(xview.str().c_str());
	      gDirectory->Delete(yview.str().c_str());
	      TH2F *Xview = new TH2F(xview.str().c_str(),"",96,-0.5,95.5,22,-0.5,21.5);
	      TH2F *Yview = new TH2F(yview.str().c_str(),"",96,-0.5,95.5,22,-0.5,21.5);	
	      Int_t colo;
	      ColorMIP(calo->estrip[l][m][n],colo);
	      Xview->SetFillColor(colo);
	      Yview->SetFillColor(colo);
	      if ( l == 0 ) {
		Xview->Fill(n,m,1.);
		pd1->cd();				    
		Xview->Draw("box same");
	      };				    
	      if ( l == 1 ) {
		Yview->Fill(n,m,1.);
		pd2->cd();
		Yview->Draw("box same");
	      };
	    } else {			    
	      if ( l == 0 ) Xview->Fill(n,m,calo->estrip[l][m][n]);
	      if ( l == 1 ) Yview->Fill(n,m,calo->estrip[l][m][n]);						    
	    };
	    if ( calo->good[l][m][n] != 0  ) badstrip++;
	  };		
	};
      };
    };
    //
    figura2->cd();
    t=new TLatex();
    t->SetTextFont(32);
    t->SetTextColor(8);
    t->SetTextAlign(12);
    t->SetTextSize(0.02);
    Int_t qtot = (int)calo->qtot;
    Int_t nstrip = (int)calo->nstrip;
    stringa.str("");
    stringa << "QTOT = " << qtot;
    stringa << "          NSTRIP = " << nstrip;
    stringa << "          Bad strips = " << badstrip;
    stringa << " ";
    t->DrawLatex(30.,2.,stringa.str().c_str());
    figura2->Update();
    if ( tyhist == "lego" ){
      pd1->cd();
      gStyle->SetOptStat(0);
      Xview->SetXTitle("strip");
      Xview->SetYTitle("X - plane");
      Xview->GetXaxis()->SetTitleOffset(1.5);
      Xview->GetYaxis()->SetTitleOffset(1.5);
      Xview->SetZTitle("MIP");	
      Xview->Draw(tyhist);
      pd1->Update();
      pd2->cd();
      gStyle->SetOptStat(0);
      Yview->SetXTitle("strip");
      Yview->SetYTitle("Y - plane");
      Yview->GetXaxis()->SetTitleOffset(1.5);
      Yview->GetYaxis()->SetTitleOffset(1.5);
      Yview->SetZTitle("MIP");
      Yview->Draw(tyhist);
      pd2->Update();
    };
    pd1->Update();
    pd2->Update();
    figura2->Update();

    //
    // Interact with user: do you want to continue, exit or print the figure?
    //
    if ( i != maxevent ) { 
      TString figty = "matra";
      doflag = 1;
      Float_t lastevno = 0;
      Float_t firstevno = 0;
      Int_t jumpto = 0;
      Int_t ifout = WhatToDo(i,doflag, jumpto,nevents,lastevno,firstevno,file,outDir,figty,*figura2);	    
      if ( maxevent < i+1 ) {
	maxevent = nevents;
	printf("WARNING: you have chosen an event number out of the starting range.\n         Range extended to %i\n\n",maxevent);		
      };
      if ( ifout ) return;
    } else {
      const string fil = (const char*)filename;
      Int_t posiz = fil.find("dw_");
      if ( posiz == -1 ) posiz = fil.find("DW_");
      Int_t posiz2 = posiz+13;
      TString file2;
      stringcopy(file2,filename,posiz,posiz2);
      //
      const char *figrec = file2;
      const char *outdir = outDir;
      stringstream figsave;    
      const char *format = saveas;
      figsave.str("");
      figsave << outdir << "/" ;
      figsave << figrec << "_matra_";
      figsave << (i+1) << ".";
      figsave << format;
      //
      figura2->SaveAs(figsave.str().c_str());
    };
    if ( doflag == 2 && i == 0 ) {
      printf("\n WARNING: Cannot go backward! Going forward. \n");
      doflag = 1;
    };
    if ( doflag == 2 && i>0 ) i--;
    if ( doflag == 1 ) i++;
  };
  //
  // last warning (if the case)
  //
  figura2->Update();
  printf("\n");
  gSystem->ChangeDirectory(startingdir);
}
