#include <physics/anticounter/AnticounterEvent.h>
#include <PscuHeader.h>
#include <EventHeader.h>

#include <TFile.h>
#include <fstream>
#include <vector>
#include <iostream>
#include <TCanvas.h>
#include <TLatex.h>
#include <TLegend.h>
#include <TLine.h>
#include <TTree.h>
#include <TStyle.h>
#include <TObjString.h>
#include <TGraph.h>
#include <TH1.h>
#include <time.h>
#include <sys/stat.h>
#include <cstdlib>
//#include <utils/yodaUtility.h>

#define DEBUG 0
#define VERSION 1.5
#define INTERVAL 100
#define FORMAT "png"

using namespace std;

UInt_t found;
Int_t minevent,maxevent;
UShort_t ACheader[2];
TString *cardname = new TString[2];
TString *detector = new TString[16];


int AcQLOOKbasic(TString base,int fromevent=0, int toevent=0, TString outDir = "./", TString format = FORMAT){

  ofstream      outputFile;
  stringstream  oss;

  pamela::anticounter::AnticounterEvent *ace      = 0;
  pamela::EventHeader                   *eh       = 0;
  //  pamela::PscuHeader                    *ph       = 0;
  TFile                                 *rootFile = new TFile(base);
  if (rootFile->IsZombie())
    exit(-1);
  TString fileName = ((TObjString*)base.Tokenize('\/')->Last())->GetString();
  TString filePath = base;
  filePath.ReplaceAll(fileName, "");
  fileName.ReplaceAll(".root", "");

  //Takes the tree of the header file                                                                                                                                              
  TTree *tr = (TTree*)rootFile->Get("Physics");

  tr->SetBranchStatus("*",0,&found); //disable all branches

  tr->SetBranchStatus("header*",1,&found);
  // printf("header: enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("status*",1,&found);
  //  printf("status: enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("hitmap*",1,&found);
  //  printf("hitmap: enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("regist*",1,&found);
  //  printf("regist: enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("shift*",1,&found);
  //  printf("shift: enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("counters*",1,&found);
  //  printf("counters: enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("coinc*",1,&found);
  //  printf("coinc: enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("trigg*",1,&found);
  //  printf("trigg: enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("clock*",1,&found);
  //  printf("clock: enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("temp*",1,&found);
  //  printf("temp: enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("DAC*",1,&found);
  //  printf("DAC: enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("CRC*",1,&found);
  //  printf("CRC: enabled %i branches \n",found);
  
  found = 0;
  tr->SetBranchStatus("Pscu*",1,&found);
  // printf("enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("Anticounter*",1,&found);
  // printf("Ac enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("Header*",1,&found);
  // printf("head enabled %i branches \n",found);
  
  tr->SetBranchAddress("Anticounter", &ace);
  tr->SetBranchAddress("Header", &eh);

  


  Int_t nevents = tr->GetEntries();

  //check that the selected range of events is ok                                                                                                                                 

  if ( fromevent > toevent && toevent ){
    return -1;
  };
  if ( fromevent > nevents || fromevent < 0 ) {
    return -1;
  };
  if ( toevent > nevents || toevent < 0 ) {
    return -1;
  };

  if ( fromevent == 0 ) {
    minevent = 0;
    maxevent = nevents;
  } else {
    minevent = fromevent - 1;
    if ( toevent > 0 ){
      maxevent = toevent;
    } else {
      maxevent = fromevent;
    };
  };

  /******************* VARIABLE DECLARATION ***************/

  ACheader[0]=0xAC11;
  ACheader[1]=0xAC22;

  detector[0]="CARD 4";
  detector[1]="CAT 2";
  detector[2]="CAS 1";
  detector[3]="NC";
  detector[4]="CARD 2";
  detector[5]="CAT 4";
  detector[6]="CAS 4";
  detector[7]="NC";
  detector[8]="CARD 3";
  detector[9]="CAT 3";
  detector[10]="CAS 3";
  detector[11]="NC";
  detector[12]="CARD 1";
  detector[13]="CAT 1";
  detector[14]="CAS 2";
  detector[15]="NC";

  
  /******************** HISTOGRAM DECLARATION *************/
  
  TH1D *hitmap_h[2];
  hitmap_h[0] = new TH1D("Hitmap MAIN","Hitmap",16,0.,16.);
  hitmap_h[1] = new TH1D("Hitmap EXTRA","Hitmap",16,0.,16.);

  TH1D *status_h = new TH1D("Status","Status",10,0.,10.);
 
  /*********************  MAIN LOOP  **********************/
  
   for (Int_t i = minevent; i < maxevent; i++){
    
     tr->GetEntry(i);
     //     ph = eh->GetPscuHeader();

    for(Int_t card=0;card<2;card++)
      {
	//Proceed only if crc is ok
	if(ace->CRCcheck[card]==1)
          {

	    //hitmap                                                                                                                                                               
            for(Int_t ch_cnt=0;ch_cnt<16;ch_cnt++)
              {
                if( (ace->hitmap[card] & (0x1<<ch_cnt)) > 0 )
                  hitmap_h[card]->Fill(ch_cnt,1.);
              }
	    //Status                                                                                                                                                               
            if((ace->header[card][0] != 0xACAC) || (ace->header[card][1] != ACheader[card]))
              status_h->Fill(1.+5.*card,1.);
            if((ace->status[card] & 0x8000) < 0x8000) //crc                                                                                                                        
              status_h->Fill(2.+5.*card,1.);
            if((ace->status[card] & 0x4000) < 0x4000) //dsp                                                                                                                        
              status_h->Fill(3.+5.*card,1.);
            if((ace->status[card] & 0x01FF) < 0x01FF) //reg                                                                                                                        
              status_h->Fill(4.+5*card,1.);

	  }//if(crc check)                                                                                                                                                         
        /******************************************************/
        else
          status_h->Fill(5.*card,1.); //event crc                                                                                                                                  
      }//for(card)         

  }//for(events)

  /***************************************** PLOTTING *****************************************/
  
  const char *namn = "KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK";
  int mposition = 80;
  int eposition = 80;
  const char *figsave1 = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";
  const char *mystring = "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD";
  
  TBox *b1,*b2,*b3,*b4,*b5;
  gStyle->SetOptDate(0); 
  TString *merr = new TString[5];
  merr[0]="Event CRC";
  merr[1]="Headers";
  merr[2]="CRC";
  merr[3]="Dsp";
  merr[4]="Reg";
  
  TCanvas *sheet1 = new TCanvas("Sheet 1","Sheet 1"); //base
  sheet1->Range(0,0,100,100);
  sheet1->Draw();
  b1 = new TBox(10,84.5,90,85.5);
  b2 = new TBox(49.5,95,50.5,5);
  b1->SetFillColor(1);
  b2->SetFillColor(1);
  b1->Draw();
  b2->Draw();
  
  TLatex *t=new TLatex();
  t->SetTextFont(40);
  t->SetTextColor(1);
  t->SetTextAlign(12);
  t->SetTextSize(0.04);
  namn = "AntiCounter MAIN card";
  t->DrawLatex(10,90,namn);
  t->SetTextColor(1);
  namn = "AntiCounter EXTRA card";
  t->DrawLatex(58,90,namn);
  t->SetTextSize(0.025);
  
  for(Int_t ch=1;ch<17;ch++)
    {
      if(ch!=4 && ch!=8 && ch!=12 && ch!=16 && hitmap_h[0]->GetBinContent(ch)==0){
	mystring = Form("%s channel empty",detector[ch-1].Data());  
	t->SetTextColor(2);
	t->DrawLatex(15,mposition,mystring);
	mposition -= 4;
      }
      if(ch!=4 && ch!=8 && ch!=12 && ch!=16 && hitmap_h[1]->GetBinContent(ch)==0){
	mystring = Form("%s channel empty",detector[ch-1].Data()); 
	t->SetTextColor(2);
	t->DrawLatex(65,eposition,mystring);
	eposition -= 4;
      }
    }
  for(Int_t ch=0;ch<5;ch++)
    {
      if(status_h->GetBinContent(ch+1)>0){
	mposition -= 4;
	mystring = Form("%d %s errors",(int)status_h->GetBinContent(ch+1),merr[ch].Data());
	t->SetTextColor(2); 
	t->DrawLatex(15,mposition,mystring);
      }
      if(status_h->GetBinContent(ch+5+1)>0){
	eposition -= 4;
	mystring = Form("%d %s errors",(int)status_h->GetBinContent(ch+5+1),merr[ch].Data());
	t->SetTextColor(2); 
	t->DrawLatex(65,eposition,mystring);
      }
    }
  //if no errors
  if(mposition==80)
    {
      namn = "AC main working";
      t->SetTextSize(0.035);
      t->SetTextColor(1); 
      t->DrawLatex(15,50,namn);
    }
  if(eposition==80)
    {
      namn = "AC extra working";
      t->SetTextSize(0.035);
      t->SetTextColor(1); 
      t->DrawLatex(65,50,namn);
    }
  if(mposition!=80 || eposition!=80)
    {
      namn = "AC malfunction";
      t->SetTextSize(0.035);
      t->SetTextColor(1);
      t->DrawLatex(41.5,97.3,namn);
      b3 = new TBox(10,96,40,98.5);
      b4 = new TBox(10,1.5,90,4);
      b5 = new TBox(60,96,90,98.5);
      b3->SetFillColor(2);
      b4->SetFillColor(2);
      b5->SetFillColor(2);
      b3->Draw();
      b4->Draw();
      b5->Draw();
    }
  
  figsave1 = Form("%s/%s_AcQLOOKbasic.%s",outDir.Data(),fileName.Data(),format.Data());
  sheet1->SaveAs(figsave1);

  return 1;
  
} //end AcBasic


int AcQLOOKpro(TString base,int fromevent=0, int toevent=0, TString outDir = "./", TString format = FORMAT){

  //Float_t startTime,stopTime;
  //Float_t time1,time2,time3,time4;

  //startTime = clock();

  ofstream 	outputFile;
  stringstream 	oss;
  
  pamela::anticounter::AnticounterEvent *ace 	  = 0;
  pamela::EventHeader 			*eh 	  = 0;
  pamela::PscuHeader 			*ph 	  = 0;  
  TFile					*rootFile = new TFile(base);  
  if (rootFile->IsZombie())
    exit(-1);
  TString fileName = ((TObjString*)base.Tokenize('\/')->Last())->GetString();
  TString filePath = base;
  filePath.ReplaceAll(fileName, "");
  fileName.ReplaceAll(".root", "");

  //Takes the tree of the header file
  TTree *tr = (TTree*)rootFile->Get("Physics");
  
  tr->SetBranchStatus("*",0,&found); //disable all branches                                                                                                                       

  tr->SetBranchStatus("header*",1,&found);
  //  printf("header: enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("status*",1,&found);
  //  printf("status: enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("hitmap*",1,&found);
  //  printf("hitmap: enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("regist*",1,&found);
  //  printf("regist: enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("shift*",1,&found);
  //  printf("shift: enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("counters*",1,&found);
  //  printf("counters: enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("coinc*",1,&found);
  //  printf("coinc: enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("trigg*",1,&found);
  //  printf("trigg: enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("clock*",1,&found);
  //  printf("clock: enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("temp*",1,&found);
  //  printf("temp: enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("DAC*",1,&found);
  //  printf("DAC: enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("CRC*",1,&found);
  //  printf("CRC: enabled %i branches \n",found);
  found = 0;
 
  tr->SetBranchStatus("Pscu*",1,&found);
  //  printf("enabled %i branches \n",found);                                                                                                                                       
  found = 0;
  tr->SetBranchStatus("Anticounter*",1,&found);
  //  printf("Ac enabled %i branches \n",found);                                                                                                                                    
  found = 0;
  tr->SetBranchStatus("Header*",1,&found);
  //  printf("head enabled %i branches \n",found);    
  
  tr->SetBranchAddress("Anticounter", &ace);
  tr->SetBranchAddress("Header", &eh);
  
  /***************************  VARIABLE DECLARATION  **************************/

  ACheader[0]=0xAC11;
  ACheader[1]=0xAC22;

  cardname[0] = "MAIN";
  cardname[1] = "EXTRA";

  detector[0]="CARD 4";
  detector[1]="CAT 2";
  detector[2]="CAS 1";
  detector[3]="NC";
  detector[4]="CARD 2";
  detector[5]="CAT 4";
  detector[6]="CAS 4";
  detector[7]="NC";
  detector[8]="CARD 3";
  detector[9]="CAT 3";
  detector[10]="CAS 3";
  detector[11]="NC";
  detector[12]="CARD 1";
  detector[13]="CAT 1";
  detector[14]="CAS 2";
  detector[15]="NC";
  
  // ANTICOUNTER VARIABLES

  Double_t ac_clock_old[2] = {-1., -1.};
  Double_t ac_clock_new[2] = {-1., -1.};
  Double_t ac_clock100_new[2] = {-1.,-1.};
  Double_t ac_clock100_old[2] = {-1.,-1.};
  Double_t ac_clock_diff[2];
  Double_t ac_clock100_diff[2];
  Double_t counter_old[2][16];
  Double_t counter_new[2][16];
  Double_t counter_diff[2][16];

  // MISC VARIABLES

  //  UInt_t obt;
  Int_t hitsCARD,hitsCAT,hitsCAS;
  Int_t interval_cnt = 0;
  Int_t paramEvent = 0;
  Int_t paramEvents;
  Int_t minevent,maxevent;
  const char *figsave = "                                                         ";
  UShort_t ACheader[2];
  ACheader[0]=0xAC11;
  ACheader[1]=0xAC22;

  vector<int> Err_type(0);
  vector<float> Err_obt(0);
  vector<int> Err_evt(0);


  Int_t *det_map = new Int_t[12];
  det_map[0]=2;
  det_map[1]=14;
  det_map[2]=10;
  det_map[3]=6;
  det_map[4]=13;
  det_map[5]=1;
  det_map[6]=9;
  det_map[7]=5;
  det_map[8]=12;
  det_map[9]=4;
  det_map[10]=8;
  det_map[11]=0;

  TString *detector = new TString[16];
  detector[0]="CARD 4";
  detector[1]="CAT 2";
  detector[2]="CAS 1";
  detector[3]="NC";
  detector[4]="CARD 2";
  detector[5]="CAT 4";
  detector[6]="CAS 4";
  detector[7]="NC";
  detector[8]="CARD 3";
  detector[9]="CAT 3";
  detector[10]="CAS 3";
  detector[11]="NC";
  detector[12]="CARD 1";
  detector[13]="CAT 1";
  detector[14]="CAS 2";
  detector[15]="NC";

  TString *cardname = new TString[2];
  cardname[0] = "MAIN";
  cardname[1] = "EXTRA";
  char histotitel[30];

  Int_t nevents = tr->GetEntries();

  //check that the selected range of events is ok
  if ( fromevent > toevent && toevent ){
    return -1;
  };
  if ( fromevent > nevents || fromevent < 0 ) {
    return -1;
  };  
  if ( toevent > nevents || toevent < 0 ) {
    return -1;
  };

  if ( fromevent == 0 ) {
    minevent = 0;
    maxevent = nevents;
  } else {
    minevent = fromevent - 1;
    if ( toevent > 0 ){
      maxevent = toevent;
    } else {
      maxevent = fromevent;
    };
  };
    
  paramEvents = (Int_t)((Float_t)nevents/(Float_t)INTERVAL);
  
  /*************************  HISTOGRAM and GRAPH DECLARATION  *******************************/

  TH1D *hitmap_h[2];
  TH1D *nmbhitpmtCARD_h = new TH1D("#hit PMTs CARD","#hit PMTs",8,0.5,8.5);
  TH1D *nmbhitpmtCAT_h = new TH1D("#hit PMTs CAT","#hit PMTs",8,0.5,8.5);
  TH1D *nmbhitpmtCAS_h = new TH1D("#hit PMTs CAS","#hit PMTs",8,0.5,8.5);
  TH1D *time_between_trigg_h[2];
  TH1D *shiftreg_h[2][16];

  for(Int_t card=0;card<2;card++)
    {
      sprintf(histotitel,"Hitmap %s",cardname[card].Data());
      hitmap_h[card] = new TH1D(histotitel,"Hitmap",16,0.,16.);

      hitmap_h[card]->GetXaxis()->SetBinLabel(1,detector[0]);
      hitmap_h[card]->GetXaxis()->SetBinLabel(2,detector[1]);
      hitmap_h[card]->GetXaxis()->SetBinLabel(3,detector[2]);
      hitmap_h[card]->GetXaxis()->SetBinLabel(4,detector[3]);
      hitmap_h[card]->GetXaxis()->SetBinLabel(5,detector[4]);
      hitmap_h[card]->GetXaxis()->SetBinLabel(6,detector[5]);
      hitmap_h[card]->GetXaxis()->SetBinLabel(7,detector[6]);
      hitmap_h[card]->GetXaxis()->SetBinLabel(8,detector[7]);
      hitmap_h[card]->GetXaxis()->SetBinLabel(9,detector[8]);
      hitmap_h[card]->GetXaxis()->SetBinLabel(10,detector[9]);
      hitmap_h[card]->GetXaxis()->SetBinLabel(11,detector[10]);
      hitmap_h[card]->GetXaxis()->SetBinLabel(12,detector[11]);
      hitmap_h[card]->GetXaxis()->SetBinLabel(13,detector[12]);
      hitmap_h[card]->GetXaxis()->SetBinLabel(14,detector[13]);
      hitmap_h[card]->GetXaxis()->SetBinLabel(15,detector[14]);
      hitmap_h[card]->GetXaxis()->SetBinLabel(16,detector[15]);
      hitmap_h[card]->GetYaxis()->SetTitle("Hits");

      sprintf(histotitel,"Time between triggers %s",cardname[card].Data());
      time_between_trigg_h[card] = new TH1D(histotitel,"Time between triggers",100,0.,0.01);
      time_between_trigg_h[card]->SetBit(TH1::kCanRebin);

      for(Int_t ch = 0; ch < 16; ch++)
	{
	  sprintf(histotitel,"Shift Register %s Ch %d",cardname[card].Data(),ch+1);
	  shiftreg_h[card][ch] = new TH1D(histotitel,detector[ch].Data(),16,0.,16.); 
	}
    }
  
  TH1D *status_h = new TH1D("Status","Status",12,0.,12.);
  status_h->GetXaxis()->SetBinLabel(1,"Headers M");
  status_h->GetXaxis()->SetBinLabel(2,"CRC M");
  status_h->GetXaxis()->SetBinLabel(3,"Dsp M");
  status_h->GetXaxis()->SetBinLabel(4,"Temp M");
  status_h->GetXaxis()->SetBinLabel(5,"Reg M");
  status_h->GetXaxis()->SetBinLabel(6,"CRC Event M");
  status_h->GetXaxis()->SetBinLabel(7,"Headers E");
  status_h->GetXaxis()->SetBinLabel(8,"CRC E");
  status_h->GetXaxis()->SetBinLabel(9,"Dsp E");
  status_h->GetXaxis()->SetBinLabel(10,"Temp E");
  status_h->GetXaxis()->SetBinLabel(11,"Reg E");
  status_h->GetXaxis()->SetBinLabel(12,"CRC Event E");
  status_h->GetYaxis()->SetTitle("# of Errors");
  status_h->SetMinimum(0);

  Double_t *temp_gr[2][4];
  for(Int_t i=0;i<2;i++)
    for(Int_t j=0;j<4;j++)
      temp_gr[i][j] = new Double_t[paramEvents+1];

  for(Int_t i=0;i<2;i++)
    for(Int_t j=0;j<4;j++)
      for(Int_t k=0;k<(paramEvents+1);k++)
	temp_gr[i][j][k] = 0.;

  Double_t *trigger_gr[2];
  trigger_gr[0] = new Double_t[paramEvents+1];
  trigger_gr[1] = new Double_t[paramEvents+1];

  Double_t *singles_gr[2][16];
  for(Int_t i=0;i<2;i++){
    for(Int_t j=0;j<16;j++){
      singles_gr[i][j] = new Double_t[paramEvents+1];
    }
  }
  for(Int_t i=0;i<2;i++){
    for(Int_t j=0;j<16;j++){
      for(Int_t k=0;k<(paramEvents+1);k++){
	singles_gr[i][j][k] = 0.;
      }
    }
  }
  
  Double_t *event_obt = new Double_t[paramEvents+1];
  

  /**********************************************************************************/

 
  /*********************  MAIN LOOP  **********************/

  //time1 = clock();
  //printf("Init time: %f\n",(Double_t) (time1 - startTime) / (Double_t) CLOCKS_PER_SEC);

  //iterators used in the loop                                                                                                                                                   
  Int_t card, ch, bin;

  for (Int_t i = minevent; i < maxevent; i++){

    interval_cnt++;
    
    tr->GetEntry(i);
    ph = eh->GetPscuHeader();
    //    obt = ph->GetOrbitalTime();    
  
    hitsCARD=hitsCAT=hitsCAS=0;
    
    for(card=0;card<2;card++)
      {
	//proceed only if crc of event is ok
	//printf("CRC: %hx\n",ace->CRCcheck[card]);
	//printf("Hitmap: %hx\n\n",ace->hitmap[card]);
	if(ace->CRCcheck[card]==1)
	  {
	    //clock
	    ac_clock_old[card] = ac_clock_new[card];
	    ac_clock_new[card] = ace->clock[card][1]*0xFFFF + ace->clock[card][0];
	    if(ac_clock_new[card] - ac_clock_old[card] < 0.)
	      ac_clock_diff[card] = 0xFFFFFFFF+ac_clock_new[card]-ac_clock_old[card];
	    else
	      ac_clock_diff[card] = ac_clock_new[card]-ac_clock_old[card];

	    if(ac_clock_old[card] > 0. && 0.000000025*ac_clock_diff[card]<10.)
	      time_between_trigg_h[card]->Fill( 0.000000025*ac_clock_diff[card] );

	    //counters, singlesrate & shift reg content
	    for(ch=0;ch<16;ch++)
	      {
		counter_old[card][ch] = counter_new[card][ch];
		counter_new[card][ch] = ace->counters[card][ch];
		if(counter_new[card][ch] - counter_old[card][ch] < 0.)
		  counter_diff[card][ch] = 0xFFFF + counter_new[card][ch] - counter_old[card][ch];
		else
		  counter_diff[card][ch] = counter_new[card][ch] - counter_old[card][ch];
		
		singles_gr[card][ch][paramEvent] += (Double_t)counter_diff[card][ch];
		
		for(bin = 0; bin < 16; bin++){
		  shiftreg_h[card][bin]->Fill(ch,ace->shift[card][ch] & 0x1<<bin); 
		}

		//hitmap
		if( (ace->hitmap[card] & (0x1<<ch)) > 0 ){
		  hitmap_h[card]->Fill(ch,1.);
		  if(ch==0 || ch==4 || ch==8 || ch==12)
		    hitsCARD++;
		  else if(ch==1 || ch==5 || ch==9 || ch==13)
		    hitsCAT++;
		  else if(ch==2 || ch==6 || ch==10 || ch==14)
		    hitsCAS++;
		}
		
	      }
	    
	    //Status
	    if((ace->header[card][0] != 0xACAC) || (ace->header[card][1] != ACheader[card])){
	      status_h->Fill(6.*card,1.);
	      Err_type.push_back(6*card);
	      Err_obt.push_back(ph->GetOrbitalTime());
	      Err_evt.push_back(i);
	    }
	    if((ace->status[card] & 0x8000) < 0x8000){ //crc
	      status_h->Fill(1.+6.*card,1.);
	      Err_type.push_back(1+6*card);
              Err_obt.push_back(ph->GetOrbitalTime());
              Err_evt.push_back(i);
	    }
	    if((ace->status[card] & 0x6000) < 0x6000){ //dsp
	      status_h->Fill(2.+6.*card,1.);
	      Err_type.push_back(2+6*card);
              Err_obt.push_back(ph->GetOrbitalTime());
              Err_evt.push_back(i);
	    }
	    if((ace->status[card] & 0x0E00) < 0x0E00){ //temp
	      status_h->Fill(3.+6.*card,1.);
	      Err_type.push_back(3+6*card);
              Err_obt.push_back(ph->GetOrbitalTime());
              Err_evt.push_back(i);
	    }
	    if((ace->status[card] & 0x01FF) < 0x01FF){ //reg
	      status_h->Fill(4.+6.*card,1.);
	      Err_type.push_back(4+6*card);
              Err_obt.push_back(ph->GetOrbitalTime());
              Err_evt.push_back(i);
	    }

	    //temperature (left on cards)
	    temp_gr[card][0][paramEvent] += ( ((ace->temp[card][0] & 0x00FF))*2.8 - 273. )/(Float_t)INTERVAL;
	    temp_gr[card][1][paramEvent] += ( ((ace->temp[card][0] & 0xFF00)/256)*2.8 - 273. )/(Float_t)INTERVAL;
	    temp_gr[card][2][paramEvent] += ( ((ace->temp[card][1] & 0x00FF))*2.8 - 273. )/(Float_t)INTERVAL;
	    temp_gr[card][3][paramEvent] += ( ((ace->temp[card][1] & 0xFF00)/256)*2.8 - 273. )/(Float_t)INTERVAL;
	    
	  }//if(crc check)
	else{
	  status_h->Fill(5.+6.*card,1.); //event crc
	  Err_type.push_back(5+6*card);
	  Err_obt.push_back(ph->GetOrbitalTime());
	  Err_evt.push_back(i);
	}
      }//for(card)

    nmbhitpmtCARD_h->Fill(hitsCARD);
    nmbhitpmtCAS_h->Fill(hitsCAS);
    nmbhitpmtCAT_h->Fill(hitsCAT);

    
    if(interval_cnt==INTERVAL)
      {
	event_obt[paramEvent] = ph->GetOrbitalTime();

	for(card=0;card<2;card++)
	  {
	    ac_clock100_old[card] = ac_clock100_new[card];
	    ac_clock100_new[card] = (ace->clock[card][1])*0xFFFF + ace->clock[card][0];
	    if((ac_clock100_new[card]-ac_clock100_old[card]) < 0.)
	      ac_clock100_diff[card] = 0xFFFFFFFF+ac_clock100_new[card]-ac_clock100_old[card];
	    else
	      ac_clock100_diff[card] = ac_clock100_new[card]-ac_clock100_old[card];

	    trigger_gr[card][paramEvent] = (Float_t)INTERVAL/(0.000000025*ac_clock100_diff[card]);

	    for(ch=0;ch<16;ch++)
	      singles_gr[card][ch][paramEvent] = singles_gr[card][ch][paramEvent]/(Double_t)(0.000000025*ac_clock100_diff[card]);
		
	  }//for(card)
	interval_cnt=0;
	paramEvent++;
      }//if(interval_cnt))
    
  } //for(events)

  //for(Int_t i=0;i<Err_type.size();i++)
  //printf("%d\t%f\t%d\n\n",Err_type.at(i),Err_obt.at(i),Err_evt.at(i));

  //Time2 = clock();
  //printf("Loop time: %f\n",(Double_t) (time2 - time1) / (Double_t) CLOCKS_PER_SEC);
  
  /******************************  PLOTTING  ***************************/
  
  TCanvas *sheet1 = new TCanvas("Sheet 1");
  sheet1->Range(0,0,100,100);
  sheet1->Draw();
  sheet1->cd();

  TLatex *t=new TLatex();
  t->SetTextFont(32);
  t->SetTextColor(1);
  t->SetTextAlign(12);
  t->SetTextSize(0.02);

  TPad *pd1 = new TPad("pd1","This is pad1",0.02,0.02,0.49,0.49,17); //lower left
  TPad *pd2 = new TPad("pd2","This is pad2",0.51,0.02,0.98,0.49,17); //lower right
  TPad *pd4 = new TPad("pd4","This is pad4",0.02,0.51,0.49,0.98,17); //upper left
  TPad *pd3 = new TPad("pd3","This is pad3",0.51,0.51,0.98,0.98,17); //upper right
      

  pd4->Range(0,0,100,100);
  sheet1->cd();
  pd1->Draw();
  pd2->Draw();
  pd3->Draw();
  pd4->Draw();

  pd4->cd();
  char namn3[30];
  char namn4[40];
  char namn5[30];
  sprintf(namn3,"Anticounter Quicklook  v%.1f",VERSION);
  sprintf(namn4,"File: %s",fileName.Data());
  sprintf(namn5,"Events: %d",nevents);
  t->SetTextSize(0.1);
  t->DrawLatex(5,90,namn3);
  t->SetTextSize(0.1);
  t->DrawLatex(20,50,namn4);
  t->DrawLatex(20,40,namn5);
  
  t->SetTextSize(0.02);

  pd3->cd();
  status_h->SetLineColor(1);
  status_h->SetStats(kFALSE);
  status_h->Draw();

  pd1->cd();
  TGraph *temperatureRIGHT_M_g = new TGraph(paramEvents,event_obt,temp_gr[0][0]);
  TGraph *temperatureACTEL_M_g = new TGraph(paramEvents,event_obt,temp_gr[0][1]);
  TGraph *temperatureLEFT_M_g = new TGraph(paramEvents,event_obt,temp_gr[0][2]);
  TGraph *temperatureDSP_M_g = new TGraph(paramEvents,event_obt,temp_gr[0][3]);
  temperatureRIGHT_M_g->SetMaximum(50.);
  temperatureRIGHT_M_g->SetMinimum(0.);
  temperatureRIGHT_M_g->SetTitle("Temperature MAIN");
  temperatureRIGHT_M_g->GetXaxis()->SetTitle("Obt [ms]");
  temperatureRIGHT_M_g->GetYaxis()->SetTitle("T [Celsius]");
  temperatureRIGHT_M_g->SetMarkerColor(1);
  temperatureACTEL_M_g->SetMarkerColor(2);
  temperatureLEFT_M_g->SetMarkerColor(3);
  temperatureDSP_M_g->SetMarkerColor(4);
  temperatureRIGHT_M_g->SetLineColor(1);
  temperatureACTEL_M_g->SetLineColor(2);
  temperatureLEFT_M_g->SetLineColor(3);
  temperatureDSP_M_g->SetLineColor(4);
  temperatureRIGHT_M_g->Draw("AL");
  temperatureACTEL_M_g->Draw("LSAME");
  temperatureLEFT_M_g->Draw("LSAME");
  temperatureDSP_M_g->Draw("LSAME");

  TLegend *legTempM = new TLegend(0.72,0.63,0.85,0.8);
  legTempM->AddEntry(temperatureRIGHT_M_g,"Right","P");
  legTempM->AddEntry(temperatureACTEL_M_g,"Actel","P");
  legTempM->AddEntry(temperatureLEFT_M_g,"Left","P");
  legTempM->AddEntry(temperatureDSP_M_g,"Dsp","P");
  legTempM->Draw();

  pd2->cd();
  TGraph *temperatureRIGHT_E_g = new TGraph(paramEvents,event_obt,temp_gr[1][0]);
  TGraph *temperatureACTEL_E_g = new TGraph(paramEvents,event_obt,temp_gr[1][1]);
  TGraph *temperatureLEFT_E_g = new TGraph(paramEvents,event_obt,temp_gr[1][2]);
  TGraph *temperatureDSP_E_g = new TGraph(paramEvents,event_obt,temp_gr[1][3]);
  temperatureRIGHT_E_g->SetTitle("Temperature EXTRA");
  temperatureRIGHT_E_g->GetXaxis()->SetTitle("Obt [ms]");
  temperatureRIGHT_E_g->GetYaxis()->SetTitle("T [Celsius]");
  temperatureRIGHT_E_g->SetMarkerColor(1);
  temperatureACTEL_E_g->SetMarkerColor(2);
  temperatureLEFT_E_g->SetMarkerColor(3);
  temperatureDSP_E_g->SetMarkerColor(4);
  temperatureRIGHT_E_g->SetLineColor(1);
  temperatureACTEL_E_g->SetLineColor(2);
  temperatureLEFT_E_g->SetLineColor(3);
  temperatureDSP_E_g->SetLineColor(4);

  
  temperatureRIGHT_E_g->SetMaximum(50.);
  temperatureRIGHT_E_g->SetMinimum(0.);
  temperatureRIGHT_E_g->Draw("AL");
  temperatureACTEL_E_g->Draw("LSAME");
  temperatureLEFT_E_g->Draw("LSAME");
  temperatureDSP_E_g->Draw("LSAME");

  TLegend *legTempE = new TLegend(0.72,0.63,0.86,0.8);
  legTempE->AddEntry(temperatureRIGHT_E_g,"Right","L");
  legTempE->AddEntry(temperatureACTEL_E_g,"Actel","L");
  legTempE->AddEntry(temperatureLEFT_E_g,"Left","L");
  legTempE->AddEntry(temperatureDSP_E_g,"Dsp","L");
  legTempE->Draw();

  /************************/

  TCanvas *sheet2 = new TCanvas("Sheet 2");
  sheet2->Range(0,0,100,100);
  sheet2->Draw();
  sheet2->cd();

  TPad *pd21 = new TPad("pd21","This is pad1",0.02,0.02,0.49,0.49,17); //lower left                                                                                               
  //TPad *pd22 = new TPad("pd22","This is pad2",0.51,0.02,0.98,0.49,17); //lower right                                                                                             
  TPad *pd22_1 = new TPad("pd22_1","This is pad22_1",0.51,0.02,0.65,0.49,17);
  TPad *pd22_2 = new TPad("pd22_3","This is pad22_2",0.67,0.02,0.81,0.49,17);
  TPad *pd22_3 = new TPad("pd22_4","This is pad22_3",0.83,0.02,0.97,0.49,17);
  
  TPad *pd24 = new TPad("pd24","This is pad4",0.02,0.51,0.49,0.98,17); //upper left                                                                                                  
  TPad *pd23 = new TPad("pd23","This is pad3",0.51,0.51,0.98,0.98,17); //upper right                                                                                                 
  sheet2->cd();
  pd21->Draw();
  pd22_1->Draw();
  pd22_2->Draw();
  pd22_3->Draw();
  pd23->Draw();
  pd24->Draw();

  t->SetTextColor(1);
  t->DrawLatex(82,99,cardname[0]);
  t->SetTextColor(2);
  t->DrawLatex(89,99,cardname[1]);

  pd24->cd();
  TGraph *triggM_gr = new TGraph(paramEvents,event_obt,trigger_gr[0]);
  TGraph *triggE_gr = new TGraph(paramEvents,event_obt,trigger_gr[1]);
  triggM_gr->SetTitle("Trigger Rate");
  triggM_gr->GetXaxis()->SetTitle("Obt [ms]");
  triggM_gr->GetYaxis()->SetTitle("f [Hz]");
  triggM_gr->SetMarkerColor(1);
  triggE_gr->SetMarkerColor(2);
  triggM_gr->SetLineColor(1);
  triggE_gr->SetLineColor(2); 
  triggM_gr->Draw("AL");
  triggE_gr->Draw("LSAME");

  pd23->cd();                                                                                                                                                                       
  gPad->SetLogy(1);                                                                                                                                                                
  time_between_trigg_h[0]->GetXaxis()->SetTitle("Time [s]");                                                                                                                       
  time_between_trigg_h[0]->SetLineColor(1);                                                                                                                                        
  time_between_trigg_h[1]->SetLineColor(2);                                                                                                                                        
  if(time_between_trigg_h[0]->GetMaximum() < time_between_trigg_h[1]->GetMaximum())                                                                                                 
    time_between_trigg_h[0]->SetMaximum(1.3*time_between_trigg_h[1]->GetMaximum());                                                                                                
  //time_between_trigg_h[0]->SetStats(kFALSE);
  time_between_trigg_h[0]->Draw();          
  time_between_trigg_h[1]->SetStats(kFALSE);
  time_between_trigg_h[1]->Draw("SAME");    
  
 
  pd21->cd();
  hitmap_h[0]->SetStats(kFALSE);
  hitmap_h[1]->SetStats(kFALSE);
  hitmap_h[0]->SetLineColor(1);
  if(hitmap_h[0]->GetMaximum() < hitmap_h[1]->GetMaximum())
    hitmap_h[0]->SetMaximum(1.1*hitmap_h[1]->GetMaximum());
  hitmap_h[0]->Draw();
  hitmap_h[1]->SetLineColor(2);
  hitmap_h[1]->Draw("SAME");

 
  pd22_1->cd();
  gPad->SetLogy(1);
  nmbhitpmtCARD_h->SetTitle("CARD");
  nmbhitpmtCARD_h->GetXaxis()->SetTitle("Nmb of hits");
  nmbhitpmtCARD_h->GetYaxis()->SetTitle("Events");
  nmbhitpmtCARD_h->SetStats(kFALSE);
  nmbhitpmtCARD_h->SetLineColor(1);
  nmbhitpmtCARD_h->Draw();

  pd22_2->cd(); 
  gPad->SetLogy(1);
  nmbhitpmtCAT_h->SetTitle("CAT");
  nmbhitpmtCAT_h->GetXaxis()->SetTitle("Nmb of hits");
  nmbhitpmtCAT_h->GetYaxis()->SetTitle("Events");
  nmbhitpmtCAT_h->SetStats(kFALSE);
  nmbhitpmtCAT_h->SetLineColor(1);
  nmbhitpmtCAT_h->Draw();

  pd22_3->cd(); 
  gPad->SetLogy(1);
  nmbhitpmtCAS_h->SetTitle("CAS");
  nmbhitpmtCAS_h->GetXaxis()->SetTitle("Nmb of hits");
  nmbhitpmtCAS_h->GetYaxis()->SetTitle("Events");
  nmbhitpmtCAS_h->SetStats(kFALSE);
  nmbhitpmtCAS_h->SetLineColor(1);
  nmbhitpmtCAS_h->Draw();

  /*
  if(nmbhitpmtCAT_h->GetMaximum() > nmbhitpmtCARD_h->GetMaximum())
    {
      if(nmbhitpmtCAT_h->GetMaximum() > nmbhitpmtCAS_h->GetMaximum())
	nmbhitpmtCARD_h->SetMaximum(1.2*nmbhitpmtCAT_h->GetMaximum());
      else
	nmbhitpmtCARD_h->SetMaximum(1.2*nmbhitpmtCAS_h->GetMaximum());
    }
  nmbhitpmtCARD_h->SetLineColor(1);
  nmbhitpmtCAT_h->SetLineColor(2);
  nmbhitpmtCAS_h->SetLineColor(3);
  nmbhitpmtCARD_h->SetMarkerStyle(20);
  nmbhitpmtCAT_h->SetMarkerStyle(21);
  nmbhitpmtCAS_h->SetMarkerStyle(22);
  nmbhitpmtCARD_h->Draw("P");
  nmbhitpmtCAT_h->Draw("PSAME");
  nmbhitpmtCAS_h->Draw("PSAME");

  TLegend *leghitpmt = new TLegend(0.72,0.63,0.86,0.8);
  leghitpmt->AddEntry(nmbhitpmtCARD_h,"CARD","P");
  leghitpmt->AddEntry(nmbhitpmtCAT_h,"CAT","P");
  leghitpmt->AddEntry(nmbhitpmtCAS_h,"CAS","P");
  leghitpmt->Draw();
  */

   /********** SHEET 3 *********/
    
  TCanvas *sheet3 = new TCanvas("Sheet 3"); 
  //sheet2->Divide(4,4);
  sheet3->Draw();
  sheet3->cd();
  
  sheet3->Range(0,0,100,100);
  
  t->SetTextFont(32);
  t->SetTextColor(1);
  t->SetTextAlign(12);
  t->SetTextSize(0.035);
  const char *namn = "                                         ";
  
  namn="Singles Rate";
  t->DrawLatex(40.,95,namn);
  namn="CAS";
  t->DrawLatex(4.,95.,namn);
  namn="CAT";
  t->DrawLatex(4.,65.,namn);
  namn="CARD";
  t->DrawLatex(4.,34.,namn);
  
  t->SetTextSize(0.02);
  namn="MAIN";
  t->DrawLatex(85,98,namn);
  t->SetTextColor(2);
  namn="EXTRA";
  t->DrawLatex(85,95,namn);
  
  Float_t pad_x1[12] = {0.,0.25,0.5,0.75,0.,0.25,0.5,0.75,0.,0.25,0.5,0.75};
  Float_t pad_x2[12] = {0.25,0.5,0.75,1.0,0.25,0.5,0.75,1.,0.25,0.5,0.75,1.};
  Float_t pad_y1[12] = {0.68,0.68,0.68,0.68,0.37,0.37,0.37,0.37,0.06,0.06,0.06,0.06};
  Float_t pad_y2[12] = {0.92,0.92,0.92,0.92,0.62,0.62,0.62,0.62,0.31,0.31,0.31,0.31};
  TPad *singles_Pads[12];
  
  char singlesname[30];
  for(Int_t ch=0;ch<12;ch++){
    sprintf(singlesname,"Pad%d",ch+1);
    singles_Pads[ch] = new TPad(singlesname,singlesname,pad_x1[ch],pad_y1[ch],pad_x2[ch],pad_y2[ch]);
    singles_Pads[ch]->Draw();
  }
  
  sheet3->cd();
  singles_gr[0][4][0]=0.;
  TGraph *singlesrate_g[2][12];
  Int_t k;
  for(Int_t card=0;card<2;card++){
    k=0;
    for(Int_t ch=0;ch<16;ch++){
      if(ch!=3 && ch!=7 && ch!= 11 && ch!=15){
      //printf("k %d ch %d\n",k,ch);
	singles_Pads[k]->cd();
	singles_gr[card][det_map[k]][0]=0.0;
	singlesrate_g[card][k] = new TGraph(paramEvents,event_obt,singles_gr[card][det_map[k]]);
	singlesrate_g[card][k]->SetLineColor(card+1);
	singlesrate_g[card][k]->GetXaxis()->SetTitle("Obt [ms]");
	singlesrate_g[card][k]->GetYaxis()->SetTitle("f [Hz]");
	singlesrate_g[card][k]->SetTitle(detector[det_map[k]].Data());
	if(card==0)
	  singlesrate_g[card][k]->Draw("AL");
	else
	  singlesrate_g[card][k]->Draw("LSAME");
	k++;
      }
    }
  }
  
  /********** SHEET 4 *********/
    
  TCanvas *sheet4 = new TCanvas("Sheet 4"); 
  //sheet2->Divide(4,4);
  sheet4->Draw();
  sheet4->cd();
  
  sheet4->Range(0,0,100,100);
  
  t->SetTextFont(32);
  t->SetTextColor(1);
  t->SetTextAlign(12);
  t->SetTextSize(0.035);
  
  namn="Shift Register Content";
  t->DrawLatex(40.,95,namn);
  namn="CAS";
  t->DrawLatex(4.,95.,namn);
  namn="CAT";
  t->DrawLatex(4.,65.,namn);
  namn="CARD";
  t->DrawLatex(4.,34.,namn);
  
  t->SetTextSize(0.02);
  namn="MAIN";
  t->DrawLatex(85,98,namn);
  t->SetTextColor(2);
  namn="EXTRA";
  t->DrawLatex(85,95,namn);

  TPad *shift_Pads[12];

  for(Int_t ch=0;ch<12;ch++){
    sprintf(singlesname,"ShiftPad%d",ch+1);
    shift_Pads[ch] = new TPad(singlesname,singlesname,pad_x1[ch],pad_y1[ch],pad_x2[ch],pad_y2[ch]);
    shift_Pads[ch]->Draw();
  }
  
  sheet4->cd();
  for(Int_t card=0;card<2;card++){
    k=0;
    for(Int_t ch=0;ch<16;ch++){
      if(ch!=3 && ch!=7 && ch!= 11 && ch!=15){
      //printf("k %d ch %d\n",k,ch);
	shift_Pads[k]->cd();
	gPad->SetLogy(1);
	shiftreg_h[card][det_map[k]]->SetStats(kFALSE);
	shiftreg_h[card][det_map[k]]->SetLineColor(1+card);
	shiftreg_h[card][det_map[k]]->SetMinimum(0.);
	shiftreg_h[card][det_map[k]]->Scale(1./shiftreg_h[card][det_map[k]]->Integral());
	if(card==0)
	  shiftreg_h[card][det_map[k]]->Draw();
	else
	  shiftreg_h[card][det_map[k]]->Draw("SAME");
	k++;
      }
    }
  }
  
  // Plot error report if any error occurs

  //char *namn6 = "KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK";
  int mposition = 80;
  int eposition = 80;
  const char *mystring = "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD";
  TString *merr; 
  TBox *b1,*b2;

  TCanvas *sheetError;

  if(Err_type.size() > 0)
    { 
      merr = new TString[12];
      merr[0]="Header";
      merr[1]="CRC";
      merr[2]="Dsp";
      merr[3]="Temp";
      merr[4]="Reg";
      merr[5]="Event CRC";
      merr[6]="Header";
      merr[7]="CRC";
      merr[8]="Dsp";
      merr[9]="Temp";
      merr[10]="Reg";
      merr[11]="Event CRC";

      sheetError = new TCanvas("Sheet Error","Sheet Error"); //base                                                                                                                       
      sheetError->Range(0,0,100,100);
      sheetError->Draw();
      b1 = new TBox(10,83.5,90,84.5);
      b2 = new TBox(49.5,90,50.5,5);
      b1->SetFillColor(1);
      b2->SetFillColor(1);
      b1->Draw();
      b2->Draw();

      t->SetTextFont(40);
      t->SetTextColor(1);
      t->SetTextAlign(12);
      t->SetTextSize(0.04);
      namn = "AntiCounter Error Report";
      t->DrawLatex(37,94,namn);
      t->SetTextColor(1);
      namn = "MAIN card";
      t->DrawLatex(15,87,namn);
      t->SetTextColor(1);
      namn = "EXTRA card";
      t->DrawLatex(65,87,namn);
      t->SetTextSize(0.015);
     

      //for(Int_t i=0;i<Err_type.size();i++)
      UInt_t iter = 0;
      while(iter<Err_type.size())
	{
	  mystring = Form("%s error obt %d \t event nmb %d",merr[Err_type.at(iter)].Data(),(int)Err_obt.at(iter),Err_evt.at(iter));
	  t->SetTextColor(2);
	  if(Err_type.at(iter) < 7 && mposition>10){
	    mposition -= 2;
	    t->DrawLatex(15,mposition,mystring);
	  }
	  else if(eposition>10){
	    eposition -= 2;
	    t->DrawLatex(65,eposition,mystring);
	  }
	  iter++;   
	}
      if(mposition<10)
	t->DrawLatex(15,5,"More errors in run!");
      if(eposition<10)
	t->DrawLatex(65,5,"More errors in run!");

      figsave = Form("%s/%s_AcQLOOK_Error.%s",outDir.Data(),fileName.Data(),format.Data());
      sheetError->SaveAs(figsave);
    }  

  figsave = Form("%s/%s_AcQLOOK_Status.%s",outDir.Data(),fileName.Data(),format.Data());  
  sheet1->SaveAs(figsave);

  figsave = Form("%s/%s_AcQLOOK_Trigger.%s",outDir.Data(),fileName.Data(),format.Data());
  sheet2->SaveAs(figsave);

  figsave = Form("%s/%s_AcQLOOK_Singles.%s",outDir.Data(),fileName.Data(),format.Data());
  sheet3->SaveAs(figsave);

  figsave = Form("%s/%s_AcQLOOK_Shift.%s",outDir.Data(),fileName.Data(),format.Data());
  sheet4->SaveAs(figsave);

  delete sheet1;
  delete hitmap_h[0];
  delete hitmap_h[1];

  //stopTime = clock();
  //printf("Draw time: %f\n\n",(Double_t) (stopTime - time2) / (Double_t) CLOCKS_PER_SEC);
  //printf("Exc time: %f\n",(Double_t) (stopTime-startTime) / (Double_t) CLOCKS_PER_SEC);

  return 1;

}


int main(int argc, char* argv[]){
    TString outDir     	= ".";
    TString format     	= FORMAT;
    int from     	= 0;
    int to		= 0;
    int mode            = 0;
    
 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: AcQLOOK 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[path]    Set the format for the output file [default  'jpg']\n");
        printf( "\t -from #          Set the starting event  [default 0]\n");
        printf( "\t -to #            Set the last event  [default 0]\n");
	printf( "\t -mode #          advanced (1) or dummy (0) mode [default 0]\n");
        exit(1);
  }

  if (!strcmp(argv[1], "-v")){
    printf("Version %.2f\n",VERSION);
    exit(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];
        }
    }

    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;
        }
    }
    
    if (!strcmp(argv[i], "-mode")) {
      if (++i >= argc){
        printf( "-mode needs arguments. \n");
        printf( "Try '--help' for more information. \n");
        exit(1);
      } else {
        mode = atoi(argv[i]);
        continue;
      }
    }

    if (!strcmp(argv[i], "-to")) {
    	if (++i >= argc){
            printf( "-to needs arguments. \n");
            printf( "Try '--help' for more information. \n");
            exit(1);
        } 
        if (isdigit(*argv[i]) && (atoi(argv[i]) > 0)) {
            to = atoi(argv[i]);
        } else {
            //err << "-to needs a integer value. \n";
            cout << "Try '--help' for more information. \n";
            exit(1);
        }
    }
    
    if (!strcmp(argv[i], "-from")) {
    	if (++i >= argc){
            printf( "-from needs arguments. \n");
            printf( "Try '--help' for more information. \n");
            exit(1);
        } 
        if (isdigit(*argv[i]) && (atoi(argv[i]) > 0)) {
            from = atoi(argv[i]);
        } else {
            //cerr << "-from needs a integer value. \n";
            cout << "Try '--help' for more information. \n";
            exit(1);
        }
    }
    
  }
  
  if(mode==0)
    AcQLOOKbasic(argv[1], from, to, outDir, format);
  else if(mode==1)
    AcQLOOKpro(argv[1], from, to, outDir, format);
  else
    printf("Wrong mode argument. Try --help for more information\n");

}
