//
//   Check for possible errors and shows raw distribution of variables coming from the DSP (no calibrations needed) - Emiliano Mocchiutti
//
//   FCaloQLOOK.c      version 1.04  (2006-03-20)
//
//   The only input needed is the path to the directory created by YODA for the data file you want to analyze.
//
//   Changelog:
//
//   1.03 - 1.04 (2006-03-20): Documentation updated.
//
//   1.02 - 1.03 (2006-03-20): Changed name of shared libraries (from FCaloQLOOK_cxx.so to libFCaloQLOOK.so).
//
//   1.01 - 1.02 (2006-03-13): Include files from YODA without "event" directory.
//
//   1.00 - 1.01 (2006-02-28): Works on YODA v6 output (single file), does not require anymore calocommon package.
//
//   0.00 - 1.00 (2006-02-28): Clone of CaloQLOOK.c (ground software).
//
#include <iostream>
#include <fstream>
//
#include <TObject.h>
#include <TString.h>
#include <TFile.h>
#include <TCanvas.h>
#include <TH1.h>
#include <TH1F.h>
#include <TH2D.h>
#include <TLatex.h>
#include <TPad.h>
#include <TPolyLine.h>
#include <TStyle.h>
#include <TSystem.h>
//
#include <PamelaRun.h>
#include <physics/calorimeter/CalorimeterEvent.h>
//
#include <FCaloQLOOKfun.h>
//
using namespace std;
//
void stringcopy(TString& s1, const TString& s2, Int_t from=0, Int_t to=0){    
    if ( to == 0 ){
	Int_t t2length = s2.Length();
	s1 = "";
	to = t2length;
    };
    for (Int_t i = from; i<to; i++){
	s1.Append(s2[i],1);
    };
}
void stringappend(TString& s1, const TString& s2){    
    Int_t t2length = s2.Length();
    for (Int_t i = 0; i<t2length; i++){
	s1.Append(s2[i],1);
    };
}

TString getFilename(const TString filename){
  const string fil = (const char*)filename;
  Int_t posiz = fil.find("dw_");
  if ( posiz == -1 ) posiz = fil.find("DW_");
  if ( posiz == -1 ) return 0;
  Int_t posiz2 = posiz+13;
  TString file2;
  stringcopy(file2,filename,posiz,posiz2);
  TString pdat(".dat");
  stringappend(file2,pdat);
  return file2;
}

void FCaloQLOOK(TString filename, Int_t fromevent=0, Int_t toevent=0, TString outDir="", TString saveas = "ps"){
  gStyle->SetPaperSize(19.,25.);
  const char* startingdir = gSystem->WorkingDirectory();
  if ( !strcmp(outDir.Data(),"") ) outDir = startingdir;
  //
  //
  ifstream myfile;
  myfile.open(filename.Data());
  if ( !myfile ){
    printf(" %s :no such file, exiting...\n\n",filename.Data());
    return;
  };
  myfile.close();
  //
  TFile *File = new TFile(filename.Data());
  TTree *tr = (TTree*)File->Get("Physics");
  if ( !tr ) {
    printf(" Physics : no such tree in %s \n",filename.Data());
    printf(" Exiting, are you sure this is a LEVEL0 not corrupted file? \n\n");
    return;
  };
  //
  // Define variables
  //
  Float_t ctshitthr = 0.65;
  Float_t cbasethr = 0.95;
  Float_t cdexythr = 0.995;
  Float_t cdexycthr = 0.95;
  //
  pamela::calorimeter::CalorimeterEvent *ce = 0;
  pamela::EventHeader *eh = 0;
  pamela::PscuHeader *ph = 0;
  //
  UInt_t found;
  tr->SetBranchStatus("*",0,&found); //disable all branches
  //
  found = 0;
  tr->SetBranchStatus("iev*",1,&found);
  //  printf("enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("dexy*",1,&found);
  //  printf("enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("stwerr*",1,&found);
  //  printf("enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("perror*",1,&found);
  //  printf("enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("cal*",1,&found);
  //  printf("enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("base*",1,&found);
  //printf("enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("Pscu*",1,&found);
  //printf("enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("Calorimeter*",1,&found);
  //printf("calo enabled %i branches \n",found);
  found = 0;
  tr->SetBranchStatus("Header*",1,&found);
  //printf("head enabled %i branches \n",found);
  //
  tr->SetBranchAddress("Calorimeter", &ce);
  tr->SetBranchAddress("Header", &eh);
  //
  Long64_t nevents    = tr->GetEntries();
  if ( nevents < 1 ) {
    printf("The file is empty!\n");
    return;
  };
  Int_t const size = nevents;
  Double_t iev2[size+1];
  Int_t ver[4][23], lver[4][23],shit[4][11], rshit[4][11], se,bl, pl, fulldiff[4],cshit, cpre[4],nullsh[4][11], lalarm[4];
  se = 0;
  pl = 0;    
  Float_t allbase = 0.;
  Int_t tshit, trshit, compdata,rawdata, errorfull, calevn1, calevn2, calevn3, calevn4, pshit[4][11];
  tshit = 0;
  trshit = 0;
  char *sezione;
  Bool_t check = false;    
  sezione = "";
  stringstream errore;
  errore.str("");
  //
  TString fififile =  getFilename(filename);
  const char *file = fififile;
  //
  // book histograms
  //
  TH1F *h1;
  TH1F *h1r;
  TH1F *hdiff;
  TH1F *Baseline;
  TH1F *Dexy;
  TH1F *Dexyc;
  TH1F *Calstriphit;
  TH1F *calev01;
  TH1F *calev23;
  TH1F *calev03;
  TH2D *calev2;

  h1 = new TH1F("C7","Strips hit, compress mode",100,0.,200.);
  h1r = new TH1F("C8","Strips hit, raw mode",100,-1,1);
  h1r->SetBit(TH1F::kCanRebin);
  hdiff = new TH1F("C6","Differences in full mode",100,-3,3);
  hdiff->SetBit(TH1F::kCanRebin);
  Baseline = new TH1F("C9","baselines",100,0,3);
  Baseline->SetBit(TH1F::kCanRebin);
  Dexy = new TH1F("C12","dexy",100,0.,37000.);
  Dexyc = new TH1F("C10","dexyc",100,0,3);
  Dexyc->SetBit(TH1F::kCanRebin);
  Calstriphit = new TH1F("C11","calstriphit[1:4]",100,0.,200.);
    
  calev01 = new TH1F("C3","|calevnum(1)-calevnum(2)|",100,0,1);
  calev01->SetBit(TH1F::kCanRebin);
  calev23 = new TH1F("C4","|calevnum(3)-calevnum(4)|",100,0,1);
  calev23->SetBit(TH1F::kCanRebin);
  calev03 = new TH1F("C5","|calevnum(1)-calevnum(4)|",100,0,1);
  calev03->SetBit(TH1F::kCanRebin);
  calev2 = new TH2D("C2","calevnum(2)%iev",3000,0.,2.,100,0.,2.);
  calev2->SetBit(TH2D::kCanRebin);
    
  //
  // run over each event and take out some variables
  //
  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 = 0;
  if ( fromevent == 0 ) {
    minevent = 0;
    maxevent = nevents -1;
  } else {
    minevent = fromevent - 1;
    if ( toevent > 0 ){
      maxevent = toevent - 1;
    } else {
      maxevent = fromevent - 1;
    };
  };
    
  for (Int_t k = 0; k < 4; k++ ){
    for (Int_t m = 0; m < 23 ; m++ ){
      ver[k][m] = 0 ;
      lver[k][m] = 0 ;
      cpre[k]=0;
      if ( m < 11 ) {
	pshit[k][m] = 0;
	nullsh[k][m] = 0;
      };
      lalarm[k] = 0;
    };
  };
  Int_t pdone, bdone;
  pdone = 0;
  bdone = 0;
  bool isCOMP = 0;
  bool isFULL = 0;
  bool isRAW = 0;
  Int_t alldexy=0;
  Int_t alldexy2=0;
  Int_t stri=0;
  Int_t fcheck = 0;
  Int_t cestw=0;
  Int_t cmask = 127 ;
  compdata = 0;
  rawdata = 0;
  errorfull = 0;   
  calevn1 = 0;
  calevn2 = 0;
  calevn3 = 0;
  calevn4 = 0;
  fulldiff[0] = 0;
  fulldiff[1] = 0;
  fulldiff[2] = 0;
  fulldiff[3] = 0;   
  printf("\n Processed events: \n\n");
  unsigned short int calev0=0;
  unsigned short int oldcalev0;
  unsigned short int calev1=0;
  unsigned short int oldcalev1;
  unsigned short int calevv2=0;
  unsigned short int oldcalev2;
  unsigned short int calev3=0;
  unsigned short int oldcalev3;
  Int_t i = minevent;
  Float_t headc = 0.;
  Float_t headco = 0.;
  Bool_t h1rcheck = false;
  Int_t intshit = 0;
  Int_t outtshit = 0;
  Int_t incshit = 0;
  Int_t outcshit = 0;
  Int_t inbase = 0;
  Int_t outbase = 0;
  Int_t indexy = 0;
  Int_t outdexy = 0;
  Int_t indexyc = 0;
  Int_t outdexyc = 0;
  while ( i < maxevent+1){
    tshit = 0;
    trshit = 0;
    tr->GetEntry(i);
    iev2[i] = ce->iev;     
    //
    ph = eh->GetPscuHeader();
    headco = headc;
    headc = ph->GetCounter();
    calevn1 += (int)abs((int)(ce->calevnum[0]-ce->calevnum[1]));
    calevn2 += (int)abs((int)(ce->calevnum[2]-ce->calevnum[3]));
    calevn3 += (int)abs((int)(ce->calevnum[0]-ce->calevnum[3]));
    calev01->Fill(abs((int)(ce->calevnum[0]-ce->calevnum[1])));
    calev23->Fill(abs((int)(ce->calevnum[2]-ce->calevnum[3])));
    calev03->Fill(abs((int)(ce->calevnum[0]-ce->calevnum[3])));
    unsigned short calvnm2 = (unsigned short)ce->calevnum[2];
    calev2->Fill(ce->iev,calvnm2);
    calevn4 += (int)ce->calevnum[2];
    oldcalev0 = calev0;
    calev0 = (int)ce->calevnum[0];
    oldcalev1 = calev1;
    calev1 = (int)ce->calevnum[1];
    oldcalev2 = calevv2;
    calevv2 = (int)ce->calevnum[2];
    oldcalev3 = calev3;
    calev3 = (int)ce->calevnum[3];
    goto jumpprintout;
    if ( (headc - headco -1.) == 0. && ((calev0 - oldcalev0 - 1) > 0 || (calev1 - oldcalev1 - 1) > 0 || (calevv2 - oldcalev2 - 1) > 0 || (calev3 - oldcalev3 - 1) > 0) ){
      if ( i != minevent ) {
	printf(" %f 0 Event %i: %i\n",headco,i,oldcalev0);
	printf(" %f 0 Event %i: %i\n",headc,i+1,calev0);	   
	printf(" %f 1 Event %i: %i\n",headco,i,oldcalev1);
	printf(" %f 1 Event %i: %i\n",headc,i+1,calev1);	   
	printf(" %f 2 Event %i: %i\n",headco,i,oldcalev2);
	printf(" %f 2 Event %i: %i\n",headc,i+1,calevv2);	   
	printf(" %f 3 Event %i: %i\n",headco,i,oldcalev3);
	printf(" %f 3 Event %i: %i\n",headc,i+1,calev3);	
	isRAW = 0;
	if ( ce->stwerr[0] & (1 << 3)) isRAW = 1;	 
	if ( (calev0 - oldcalev0 - 1) > 0 && !isRAW && ce->perror[0] != 129 && oldcalev0 != 0) {
	  ver[0][10]++;
	};
	isRAW = 0;
	if ( ce->stwerr[0] & (1 << 3)) isRAW = 1;	 
	if ( (calev1 - oldcalev1 - 1) > 0 && !isRAW && ce->perror[1] != 129 && oldcalev1 != 0 ){
	  ver[1][10]++;
	};
	isRAW = 0;
	if ( ce->stwerr[0] & (1 << 3)) isRAW = 1;	 
	if ( (calevv2 - oldcalev2 - 1) > 0 && !isRAW && ce->perror[2] != 129 && oldcalev2 != 0 ){
	  ver[2][10]++;
	};
	isRAW = 0;
	if ( ce->stwerr[0] & (1 << 3)) isRAW = 1;	 
	if ( (calev3 - oldcalev3 - 1) > 0 && !isRAW && ce->perror[3] != 129 && oldcalev3 != 0 ){
	  ver[3][10]++;
	};
      }
    };
  jumpprintout:
    memcpy(shit, nullsh, sizeof(nullsh));
    memcpy(rshit, nullsh, sizeof(nullsh));
    for (Int_t l = 0; l < 2; l++ ){
      for (Int_t ii = 0; ii < 22; ii++){
	if (l == 0 && ii%2 == 0){
	  se = 3;
	  pl = ii/2;
	  pdone = 0;
	};
	if (l == 0 && ii%2 != 0){
	  se = 2;
	  pl = (ii-1)/2;
	  pdone = 0;
	};
	if (l == 1 && ii%2 == 0){
	  se = 0;
	  pl = ii/2;
	  pdone = 0;
	};
	if (l == 1 && ii%2 != 0){
	  se = 1;
	  pl = (ii-1)/2;
	  pdone = 0;
	};
		
	isCOMP = 0;
	isFULL = 0;
	isRAW = 0;
	if ( ce->stwerr[se] & (1 << 16) ) isCOMP = 1; 
	if ( ce->stwerr[se] & (1 << 17) ) isFULL = 1; 
	if ( ce->stwerr[se] & (1 << 3) ) isRAW = 1; 
	bl = -1;
	for (Int_t kk = 0; kk < 96 ; kk++ ){
	  if ( kk%16 == 0 ){
	    bdone = 0;
	    bl++;
	    allbase = ce->base[l][ii][bl];
	    alldexy=0;
	    alldexy2=0;
	    stri=0;
	    for (Int_t e = 0; e < 16 ; e++ ){
	      stri = e + 16 * bl;
	      alldexy += (int)ce->dexyc[l][ii][stri];
	      alldexy2 += (int)ce->dexy[l][ii][stri];
	    };
	  };
	  if ( !isRAW ) {
	    //
	    if ( !pdone ){
	      if ( (ce->base[l][ii][bl]>32000 || ce->base[l][ii][bl] == 0 ) && ( alldexy > 512000 ||  alldexy == 0) && ce->perror[se] == 0 ) {
		pdone = 1;
		pshit[se][pl]++ ;
		if ( (ce->stwerr[se] & (1 << 4)) == 0 ) lalarm[se]++;
		lver[se][2]++ ;
	      };
	    }
	    //
	    if ( !bdone ){ 
	      Baseline->Fill(ce->base[l][ii][bl]);
	      if ( ce->base[l][ii][bl] > 2000. && ce->base[l][ii][bl] < 4500. ){
		inbase++;
	      } else { 
		outbase++;
	      };
	      bdone = 1;
	    };
	    //
	    if (ce->dexyc[l][ii][kk] > 0 ) {
	      shit[se][pl]++ ;
	      compdata = 1;
	    };
	    //
	    if ( isFULL ) {
	      if ( ce->dexy[l][ii][kk] > 0 && ce->dexy[l][ii][kk] < 32000 ) {
		rshit[se][pl]++ ;
		rawdata = 1;
	      };
	      Dexy->Fill(ce->dexy[l][ii][kk]);
	      if ( ce->dexy[l][ii][kk] < 2000. || ce->dexy[l][ii][kk] > 5000. ) {
		outdexy++;
	      } else {
		indexy++; 			    
	      };
	      if ( ce->dexyc[l][ii][kk]>0 && (ce->dexy[l][ii][kk]-ce->dexyc[l][ii][kk]) != 0 && ce->perror[se] != 132 && (ce->base[l][ii][bl] == 0 || ce->base[l][ii][bl] >32000) ){
		hdiff->Fill(ce->dexyc[l][ii][kk]-ce->dexy[l][ii][kk]);
		fulldiff[se]++;
		errorfull = 1;
	      };
	    };
	    //
	    Dexyc->Fill(ce->dexyc[l][ii][kk]);
	    if ( ce->dexyc[l][ii][kk] != 0. && ( ce->dexyc[l][ii][kk] < 2000. || ce->dexyc[l][ii][kk] > 5000. ) ) {
	      outdexyc++;
	    } else {
	      indexyc++; 			    
	    };
	    //
	    if (ce->dexyc[l][ii][kk] < 0 ) ver[se][21]++ ;
	    //
	    if ( allbase == 0. || allbase > 32000.) {
	      fcheck = 0;
	      for (Int_t nn = bl*16; nn < (bl+1)*16 ; nn++){
		if ( ce->dexyc[l][ii][nn] > 0. &&  ce->dexyc[l][ii][nn] < 32000. ) fcheck++;   
	      };				    
	      if ( fcheck ) {
		cpre[se]++;
		allbase = 1.;
	      };
	    };
	    //
	  } else {
	    if ( !pdone ){
	      if ( (alldexy2>512000 || alldexy2 == 0) && ce->perror[se] == 0 ) {
		pdone = 1;
		pshit[se][pl]++ ;			 
		if ( (ce->stwerr[se] & (1 << 4)) == 0 ) lalarm[se]++;
		lver[se][2]++ ;
	      };
	    };
	    if ( ce->dexy[l][ii][kk] > 0 && ce->dexy[l][ii][kk] < 32000 ) {
	      rshit[se][pl]++ ;
	      rawdata = 1;
	    };
	    Dexy->Fill(ce->dexy[l][ii][kk]);
	    if ( ce->dexy[l][ii][kk] < 2000. || ce->dexy[l][ii][kk] > 5000. ) {
	      outdexy++;
	    } else {
	      indexy++; 			    
	    };
	  };
	};
      };
    };
    cshit = 0;
    for (Int_t k = 0; k < 4 ; k++ ){
      isCOMP = 0;
      isFULL = 0;
      if ( ce->stwerr[se] & (1 << 16) ) isCOMP = 1; 
      if ( ce->stwerr[se] & (1 << 17) ) isFULL = 1; 
      if ( isCOMP ) ver[k][16]++;
      if ( isFULL ) ver[k][17]++;
      cshit += (int)ce->calstriphit[k];
      cestw=0;
      if ( ce->stwerr[k] ) cestw =  ce->stwerr[k] & cmask ;
      if ( cestw ){
	if ( cestw & (1 << 0) ) ver[k][6]++ ;
	if ( cestw & (1 << 1) ) ver[k][5]++ ;
	if ( cestw & (1 << 2) )	ver[k][4]++ ;
	if ( cestw & (1 << 3) ) ver[k][3]++ ;
	if ( cestw & (1 << 4) ) ver[k][2]++ ;
	if ( cestw & (1 << 5) ) ver[k][1]++ ;
	if ( cestw & (1 << 6) ) ver[k][0]++ ;		
      };
      if ( ce->perror[k] != 0. ){
	if (ce->perror[k] == 128) ver[k][7]++ ; 
	if (ce->perror[k] == 129) ver[k][8]++ ; 
	if (ce->perror[k] == 132) ver[k][11]++ ; 
	if (ce->perror[k] == 133) ver[k][12]++ ; 
	if (ce->perror[k] == 134) ver[k][13]++ ; 
	if (ce->perror[k] == 135) ver[k][14]++ ; 
	if (ce->perror[k] == 136) ver[k][15]++ ; 
	if (ce->perror[k] == 139) ver[k][18]++ ; 
	if (ce->perror[k] == 140) ver[k][19]++ ; 
	if (ce->perror[k] == 141) ver[k][20]++ ; 
	if (ce->perror[k] == 142) ver[k][22]++ ; 
      };
      for (Int_t kk = 0; kk < 11 ; kk++ ){
	tshit += shit[k][kk];
	trshit += rshit[k][kk];
      };
    };	
    Calstriphit->Fill(cshit);
    if ( (cshit > 0 && cshit < 25) || (cshit > 40 && cshit < 80) ){
      incshit++;
    } else {
      outcshit++;
    };
    if ( tshit>0 ) h1->Fill(tshit);
    if ( (tshit > 0 && tshit < 25) || (tshit > 40 && tshit < 80) ){
      intshit++;
    } else {
      outtshit++;
    };
    if ( trshit>0 ) {
      h1r->Fill(trshit);
      if ( trshit < 4210 ){
	h1rcheck = true;
	//		printf("ma come... trshit %i \n",trshit);
      };
    };
    if ( i%1000 == 0 && i > 0 ) printf("%iK\n",i/1000);
    i++;
  };
  printf("\n");
    
  //
  //  output figures, first sheet:
  //
  gStyle->SetOptDate(0);   
  gStyle->SetOptStat(1111);   
  TCanvas *figura = new TCanvas("Calorimeter_Detector_Report_1/3", "Calorimeter_Detector_Report_1/3", 1100, 900);
  figura->SetFillColor(10);
  figura->Range(0,0,100,100);
  errore.str("");
  errore << "EXPERT  --  File: " << file;
  errore << " ";
  TLatex *t=new TLatex();
  t->SetTextFont(32);
  t->SetTextColor(1);
  t->SetTextAlign(12);
  t->SetTextSize(0.015);
  t->DrawLatex(2.,99.,errore.str().c_str());
  TPad *pd5;
  TPad *pd6;
  TPad *pad1;
  TPad *pad2;
  TPad *pad3;
  TPad *pad4;
  TPad *pd1;
  TPad *pd2;
  TPad *pd3;
  TPad *pd4;
  //
  Double_t h1max;
  TPolyLine *banda1;
  TPolyLine *banda2;
  Float_t ctshit = 0;
  Float_t ccshit = 0;
  Float_t cbase = 0;
  Float_t cdexy = 0;
  Float_t cdexyc = 0;
  //
  if ( compdata && rawdata ){
    ctshit = (float)intshit/((float)outtshit + (float)intshit);
    Int_t pd5col = 10;
    Int_t pd6col = 10;
    if ( ctshit < ctshitthr ) { 
      check = true;	
      pd5col = 45;
    };
    if ( h1rcheck ) {
      check = true;
      pd6col = 45;
    };
    pd5 = new TPad("pd5","This is pad5",0.51,0.51,0.98,0.98,pd5col);
    pd6 = new TPad("pd6","This is pad6",0.51,0.02,0.98,0.49,pd6col);
    pd5->SetTicks();
    pd6->SetTicks();
    pd5->Range(0,0,100,100);
    pd6->Range(0,0,100,100);
    figura->cd();
    pd5->Draw();
    pd5->cd();
    h1->SetXTitle("Number of hit (dexyc>0)");
    h1->SetYTitle("Number of events");
    h1->Draw();
    //
    h1max = h1->GetMaximum()*1.05;
    Double_t xc[4] = {0.,25.,25.,0.};
    Double_t yc[4] = {0.,0.,h1max,h1max};
    banda1 = new TPolyLine(4,xc,yc);
    banda1->SetLineColor(5);
    banda1->SetFillColor(5);
    banda1->SetLineWidth(1);
    banda1->Draw("fSAME");
    Double_t xd[4] = {40.,80.,80.,40.};
    Double_t yd[4] = {0.,0.,h1max,h1max};
    banda2 = new TPolyLine(4,xd,yd);
    banda2->SetLineColor(5);
    banda2->SetFillColor(5);
    banda2->SetLineWidth(1);
    banda2->Draw("fSAME");
    h1->Draw("SAME");
    //
    figura->cd();
    pd6->Draw();
    pd6->cd();
    gPad->SetLogy();
    h1r->SetXTitle("Number of hit (dexy>0)");
    h1r->SetYTitle("Number of events");
    h1r->Draw();
    h1max = h1r->GetMaximum()*2.05;
    Double_t xg[4] = {4220.,4230.,4230.,4220.};
    Double_t yg[4] = {0.,0.,h1max,h1max};
    banda1 = new TPolyLine(4,xg,yg);
    banda1->SetLineColor(5);
    banda1->SetFillColor(5);
    banda1->SetLineWidth(1);
    banda1->Draw("fSAME");
    h1r->Draw("SAME");
  };
  if ( (compdata && !rawdata) || (!compdata && rawdata) ){
    if ( tshit !=0 ) {
      ctshit = (float)intshit/((float)outtshit + (float)intshit);
      Int_t pd5col = 10;
      if ( ctshit < ctshitthr ) {
	check = true;
	pd5col = 45;
      };
      pd5 = new TPad("pd5","This is pad5",0.51,0.02,0.98,0.98,pd5col);
      pd5->Range(0,0,100,100);
      pd5->SetTicks();
      pd5->Draw();
      pd5->cd(); 
      h1->SetXTitle("Number of hit (dexyc>0)");
      h1->SetYTitle("Number of events");
      h1->Draw();
      h1max = h1->GetMaximum()*1.05;
      Double_t xe[4] = {0.,25.,25.,0.};
      Double_t ye[4] = {0.,0.,h1max,h1max};
      banda1 = new TPolyLine(4,xe,ye);
      banda1->SetLineColor(5);
      banda1->SetFillColor(5);
      banda1->SetLineWidth(1);
      banda1->Draw("fSAME");
      Double_t xf[4] = {40.,80.,80.,40.};
      Double_t yf[4] = {0.,0.,h1max,h1max};
      banda2 = new TPolyLine(4,xf,yf);
      banda2->SetLineColor(5);
      banda2->SetFillColor(5);
      banda2->SetLineWidth(1);
      banda2->Draw("fSAME");
      h1->Draw("SAME");
    };
    if ( trshit !=0 ) {
      Int_t pd5col = 10;
      if ( h1rcheck ) {
	check = true;
	pd5col = 45;
      };
      pd5 = new TPad("pd5","This is pad5",0.51,0.02,0.98,0.98,pd5col);
      pd5->Range(0,0,100,100);
      pd5->SetTicks();
      pd5->Draw();
      pd5->cd(); 
      gPad->SetLogy();
      h1r->SetXTitle("Number of hit (dexyc>0 or dexy>0)");
      h1r->SetYTitle("Number of events");
      h1r->Draw();
      h1max = h1r->GetMaximum()*2.05;
      Double_t xh[4] = {4220.,4230.,4230.,4220.};
      Double_t yh[4] = {0.,0.,h1max,h1max};
      banda1 = new TPolyLine(4,xh,yh);
      banda1->SetLineColor(5);
      banda1->SetFillColor(5);
      banda1->SetLineWidth(1);
      banda1->Draw("fSAME");
      h1r->Draw("SAME");
    };
  };
  if ( !errorfull ) {
    if ( calevn1 || calevn2 || calevn3 ) {
      pd1 = new TPad("pd1","This is pad1",0.02,0.51,0.24,0.98,45);
      pd2 = new TPad("pd2","This is pad2",0.26,0.51,0.49,0.98,45);
      pd3 = new TPad("pd3","This is pad3",0.02,0.02,0.24,0.49,45);
      pd4 = new TPad("pd4","This is pad4",0.26,0.02,0.49,0.49,45);
      figura->cd();
      //	    printf("ou2! \n");
      check = true;
      pd1->Range(0,0,100,100);
      pd2->Range(0,0,100,100);
      pd3->Range(0,0,100,100);
      pd4->Range(0,0,100,100);       
      pd1->Draw();
      pd2->Draw();
      pd3->Draw();
      pd4->Draw();
	    
      pd1->cd();
      gPad->SetLogy();
      calev01->SetXTitle("delta calevnum 1-2");
      calev01->SetYTitle("Number of events");
      calev01->Draw();
	    
      pd2->cd();
      gPad->SetLogy();
      calev23->SetXTitle("delta calevnum 3-4");
      calev23->SetYTitle("Number of events");
      calev23->Draw();
	    
      pd3->cd();
      gPad->SetLogy();
      calev03->SetXTitle("delta calevnum 1-4");
      calev03->SetYTitle("Number of events");
      calev03->Draw();
	    
      pd4->cd();
      calev2->SetYTitle("calevnum 2");
      calev2->SetXTitle("iev");
      calev2->Draw();
    } else {
      if ( calevn4 ) {
	pd3 = new TPad("pd3","This is pad3",0.02,0.02,0.49,0.98,10);
	figura->cd();
	pd3->Range(0,0,100,100);
	pd3->Draw();
	pd3->cd();
	calev2->SetYTitle("calevnum 2");
	calev2->SetXTitle("iev");
	calev2->Draw();
      } else {
	figura->cd();
	t=new TLatex();
	t->SetTextFont(32);
	t->SetTextColor(1);
	t->SetTextSize(0.04);
	t->SetTextAlign(12);
	t->DrawLatex(10.,49.,"No calevnum infos from DSP");	       
      };
    };
  } else {    
    figura->cd();
    check = true;
    //	printf("nou! \n");
    pd1 = new TPad("pd1","This is pad1",0.02,0.02,0.49,0.98,45);
    pd1->Range(0,0,100,100);
    pd1->Draw();
    pd1->cd(); 
    gPad->SetLogy();
    hdiff->SetXTitle("Differences in FULL mode");
    hdiff->SetYTitle("Number of events");
    hdiff->Draw();
  };
    
  //
  //  output figures, second sheet:
  //
  TCanvas *figura2 = new TCanvas("Calorimeter_Detector_Report_2/3","Calorimeter_Detector_Report_2/3", 1100, 900);
  if ( compdata ){
    Int_t pd1col = 10;
    Int_t pd2col = 10;
    Int_t pd3col = 10;
    Int_t pd4col = 10;
    if ( (outdexy+indexy) ) { 
      cdexy = (float)indexy/((float)outdexy + (float)indexy);
      if ( cdexy < cdexythr ) {
	check = true;
	pd4col = 45;
      };	
    };
    if ( (outcshit+incshit) ) {
      ccshit = (float)incshit/((float)outcshit + (float)incshit);
      if ( ccshit < ctshitthr ) {	    
	check = true;
	pd3col = 45;
      };
    };
    if ( (outdexyc+indexyc) ) { 
      cdexyc = (float)indexyc/((float)outdexyc + (float)indexyc);
      if ( cdexyc < cdexycthr ) {
	check = true;
	pd2col = 45;
      };	
    };
    if ( (outbase+inbase) ) { 
      cbase = (float)inbase/((float)outbase + (float)inbase);
      if ( cbase < cbasethr ) {
	check = true;
	pd1col = 45;
      };	
    };
    figura2->SetFillColor(10);
    figura2->Range(0,0,100,100);
    errore.str("");
    errore << "EXPERT  --  File: " << file;
    errore << " ";
    t=new TLatex();
    t->SetTextFont(32);
    t->SetTextColor(1);
    t->SetTextAlign(12);
    t->SetTextSize(0.015);
    t->DrawLatex(2.,99.,errore.str().c_str());
    pd1 = new TPad("pd1","This is pad1",0.02,0.51,0.49,0.98,pd1col);
    pd2 = new TPad("pd2","This is pad2",0.51,0.51,0.98,0.98,pd2col);
    pd3 = new TPad("pd3","This is pad3",0.02,0.02,0.49,0.49,pd3col);
    pd4 = new TPad("pd4","This is pad4",0.51,0.02,0.98,0.49,pd4col);
    figura2->cd();
    pd1->Range(0,0,100,100);
    pd2->Range(0,0,100,100);
    pd3->Range(0,0,100,100);
    pd4->Range(0,0,100,100);       
    pd1->SetTicks();
    pd2->SetTicks();
    pd3->SetTicks();
    pd4->SetTicks();
    pd1->Draw();
    pd2->Draw();
    pd3->Draw();
    pd4->Draw();
    pd1->cd();
    Baseline->SetXTitle("ADC channels");
    Baseline->SetYTitle("Number of events");
    Baseline->Draw();
    h1max = Baseline->GetMaximum()*1.05;
    Double_t xc[4] = {2000.,4500.,4500.,2000.};
    Double_t yc[4] = {0.,0.,h1max,h1max};
    banda1 = new TPolyLine(4,xc,yc);
    banda1->SetLineColor(5);
    banda1->SetFillColor(5);
    banda1->SetLineWidth(1);
    banda1->Draw("fSAME");
    Baseline->Draw("SAME");
    //
    pd2->cd();
    gPad->SetLogy();
    Dexyc->SetXTitle("ADC channels");
    Dexyc->SetYTitle("Number of events");
    Dexyc->Draw();
    h1max = Dexyc->GetMaximum()*2.05;
    Double_t xe[4] = {2000.,5000.,5000.,2000.};
    Double_t ye[4] = {0.,0.,h1max,h1max};
    banda1 = new TPolyLine(4,xe,ye);
    banda1->SetLineColor(5);
    banda1->SetFillColor(5);
    banda1->SetLineWidth(1);
    banda1->Draw("fSAME");
    Double_t xj[4] = {0.,40.,40.,0.};
    Double_t yj[4] = {0.,0.,h1max,h1max};
    banda2 = new TPolyLine(4,xj,yj);
    banda2->SetLineColor(5);
    banda2->SetFillColor(5);
    banda2->SetLineWidth(1);
    banda2->Draw("fSAME");
    Dexyc->Draw("SAME");
    //
    pd3->cd();
    Calstriphit->SetXTitle("Number of hit");
    Calstriphit->SetYTitle("Number of events");
    Calstriphit->Draw();
    h1max = Calstriphit->GetMaximum()*1.05;
    Double_t xg[4] = {0.,25.,25.,0.};
    Double_t yg[4] = {0.,0.,h1max,h1max};
    banda1 = new TPolyLine(4,xg,yg);
    banda1->SetLineColor(5);
    banda1->SetFillColor(5);
    banda1->SetLineWidth(1);
    banda1->Draw("fSAME");
    Double_t xh[4] = {40.,80.,80.,40.};
    Double_t yh[4] = {0.,0.,h1max,h1max};
    banda2 = new TPolyLine(4,xh,yh);
    banda2->SetLineColor(5);
    banda2->SetFillColor(5);
    banda2->SetLineWidth(1);
    banda2->Draw("fSAME");
    Calstriphit->Draw("SAME");
    //
    pd4->cd();
    Dexy->SetXTitle("ADC channels");
    Dexy->SetYTitle("Number of events");
    Dexy->Draw();
    h1max = Dexy->GetMaximum()*1.05;
    Double_t xd[4] = {2000.,5000.,5000.,2000.};
    Double_t yd[4] = {0.,0.,h1max,h1max};
    banda1 = new TPolyLine(4,xd,yd);
    banda1->SetLineColor(5);
    banda1->SetFillColor(5);
    banda1->SetLineWidth(1);
    banda1->Draw("fSAME");
    Dexy->Draw("SAME");
  } else {
    Int_t pd4col = 10;
    if ( (outdexy+indexy) ) { 
      cdexy = (float)indexy/((float)outdexy + (float)indexy);
      if ( cdexy < cdexythr ) {
	check = true;
	pd4col = 45;
      };	
    };
    figura2->SetFillColor(10);
    figura2->Range(0,0,100,100);
    errore.str("");
    errore << "EXPERT  --  File: " << file;
    errore << " ";
    t=new TLatex();
    t->SetTextFont(32);
    t->SetTextColor(1);
    t->SetTextAlign(12);
    t->SetTextSize(0.015);
    t->DrawLatex(2.,99.,errore.str().c_str());
    pd4 = new TPad("pd4","This is pad4",0.02,0.02,0.98,0.98,pd4col);
    figura2->cd();
    pd4->Range(0,0,100,100);       
    pd4->SetTicks();
    pd4->Draw();
    //
    pd4->cd();
    Dexy->SetXTitle("ADC channels");
    Dexy->SetYTitle("Number of events");
    Dexy->Draw();
    h1max = Dexy->GetMaximum()*1.05;
    Double_t xd[4] = {2000.,5000.,5000.,2000.};
    Double_t yd[4] = {0.,0.,h1max,h1max};
    banda1 = new TPolyLine(4,xd,yd);
    banda1->SetLineColor(5);
    banda1->SetFillColor(5);
    banda1->SetLineWidth(1);
    banda1->Draw("fSAME");
    Dexy->Draw("SAME");
  };   
  //
  //  output figures, report sheet:
  //
  TCanvas *rapporto= new TCanvas("Calorimeter_Detector_Report_3/3", "Calorimeter_Detector_Report_3/3", 1100, 900);
  rapporto->SetFillColor(10);
  rapporto->Range(0,0,100,100);
  t=new TLatex();
  t->SetTextFont(32);
  t->SetTextColor(1);
  t->SetTextSize(0.05);
  t->SetTextAlign(12);
  //    t->DrawLatex(33.,95.,"Calorimeter quick look: ");
  errore.str("");
  errore << "BASIC: C1 - File: " << file;
  errore << " ";
  t->SetTextSize(0.02);
  t->DrawLatex(2.,99.,errore.str().c_str());
    
  pad1 = new TPad("pad1","This is pad1",0.02,0.47,0.49,0.90,19);
  pad2 = new TPad("pad2","This is pad2",0.51,0.47,0.98,0.90,19);
  pad3 = new TPad("pad3","This is pad3",0.02,0.02,0.49,0.45,19);
  pad4 = new TPad("pad4","This is pad4",0.51,0.02,0.98,0.45,19);
  pad1->Range(0,0,100,100);
  pad2->Range(0,0,100,100);
  pad3->Range(0,0,100,100);
  pad4->Range(0,0,100,100);
    
  pad1->Draw();
  pad2->Draw();
  pad3->Draw();
  pad4->Draw();

  for (Int_t i = 0; i < 4; i++){
    if (i == 2) 
      { 
	pad1->cd() ; 
	sezione = "** Section YE (x even) **";
      }
    if (i == 3) 
      {
	pad2->cd();
	sezione = "** Section YO (x odd) **";
      }
    if (i == 0)
      {
	pad3->cd();
	sezione = "** Section XE (y odd) **";
      }
    if (i == 1)
      {
	pad4->cd();
	sezione = "** Section XO (y even) **";
      }
    t->SetTextFont(32);
    t->SetTextColor(1); 
    t->SetTextSize(0.05); 
    t->SetTextAlign(12);
    t->DrawLatex(33.,97.,sezione);
    t->SetTextSize(0.05); 
    for (Int_t j = 0; j < 23; j++){
      if ( ver[i][j] || lver[i][j] ) {
	t->SetTextColor(50); 
	if (j == 0) {
	  errore.str("");
	  errore << "* DSP ack error: " << ver[i][j];
	  errore << " time(s)";
	  t->DrawLatex(2.,30.,errore.str().c_str());
	  check = true;
	}
	if (j == 1) {
	  errore.str("");
	  errore << "* Temperature alarm: " << ver[i][j];
	  errore << " time(s)";
	  t->DrawLatex(2.,74.,errore.str().c_str());
	  check = true;
	}
	if (j == 2) {
	  if ( lalarm[i] ){
	    errore.str("");
	    errore << "* Latch up: " << ver[i][j];
	    errore << " (" << lalarm[i];	
	    errore << " NOT rec!): ";
	    t->DrawLatex(0.,70.,errore.str().c_str());
	    check = true;
	  } else {
	    errore.str("");
	    errore << "* Latch up alarm: " << ver[i][j];
	    errore << " time(s). View(s): ";
	    t->DrawLatex(2.,70.,errore.str().c_str());
	    check = true;
	  };
	  errore.str("");
	  errore << "(" << lver[i][j];
	  errore << " view(s))";
	  t->DrawLatex(27.,65.,errore.str().c_str());
	  Float_t inc=1.;
	  for (Int_t e = 0; e < 11; e++){
	    if ( pshit[i][e] ) {
	      errore.str("");
	      errore << "  " << (e+1);
	      errore << "  ";
	      t->DrawLatex(52.+inc,69.,errore.str().c_str());
	      Int_t numer = pshit[i][e];
	      errore.str("");
	      errore << "  (" << numer;
	      errore << ")  ";
	      t->SetTextAngle(-70);
	      t->DrawLatex(55.+inc,67.,errore.str().c_str());
	      t->SetTextAngle(0);
	      inc += 4.;
	    }
	  }		   
	}
	if (j == 3) {
	  errore.str("");
	  errore << "RAW mode: " << ver[i][j];
	  errore << " time(s)";
	  t->SetTextColor(32); 
	  t->DrawLatex(2.,90.,errore.str().c_str());
	}
	if (j == 4) {
	  errore.str("");
	  errore << "* CMD length error: " << ver[i][j];
	  errore << " time(s)";
	  t->DrawLatex(2.,66.,errore.str().c_str());
	  check = true;
	}	       
	if (j == 5) {
	  errore.str("");
	  errore << "* Execution error: " << ver[i][j];
	  errore << " time(s)";
	  t->DrawLatex(2.,62.,errore.str().c_str());
	  check = true;
	}
	if (j == 6) {
	  errore.str("");
	  errore << "* CRC error (st. word): " << ver[i][j];
	  errore << " time(s)";
	  t->DrawLatex(2.,58.,errore.str().c_str());
	  check = true;
	}
	if (j == 7) {
	  errore.str("");
	  errore << "View or command not recognized: " << ver[i][j];
	  errore << " time(s)";
	  t->DrawLatex(2.,54.,errore.str().c_str());
	  check = true;
	}
	if (j == 8) {
	  errore.str("");
	  errore << "Missing section: " << ver[i][j];
	  errore << " time(s)";
	  t->DrawLatex(2.,50.,errore.str().c_str());
	  check = true;
	}
	if (j == 10) {
	  errore.str("");
	  errore << "Calevnum jump: " << ver[i][j];
	  errore << " time(s)";
	  t->DrawLatex(2.,42.,errore.str().c_str());
	  check = true;
	} 
	if (j == 11) {
	  errore.str("");
	  errore << "CRC error (data): " << ver[i][j];
	  errore << " time(s)";
	  t->DrawLatex(2.,38.,errore.str().c_str());
	  check = true;
	}
	if (j == 12) {
	  errore.str("");
	  errore << "Length problems in RAW mode: " << ver[i][j];
	  errore << " time(s)";
	  t->DrawLatex(2.,34.,errore.str().c_str());
	  check = true;
	}
	if (j == 13) { 
	  errore.str("");
	  errore << "Length problems in COMPRESS mode: " << ver[i][j];
	  errore << " time(s)";
	  t->DrawLatex(2.,34.,errore.str().c_str());
	  check = true;
	}
	if (j == 14) {
	  errore.str("");
	  errore << "Length problems in FULL mode: " << ver[i][j];
	  errore << " time(s)";
	  t->DrawLatex(2.,26.,errore.str().c_str());
	  check = true;
	}
	if (j == 15) {
	  errore.str("");
	  errore << "Acquisition mode problems: " << ver[i][j];
	  errore << " time(s)";
	  t->DrawLatex(2.,22.,errore.str().c_str());
	  check = true;
	}
	if (j == 16) {
	  errore.str("");
	  errore << "COMPRESS mode: " << ver[i][j];
	  errore << " time(s)";
	  t->SetTextColor(32); 
	  t->DrawLatex(2.,86.,errore.str().c_str());
	}
	if (j == 17) {
	  errore.str("");
	  errore << "FULL mode: " << ver[i][j];
	  errore << " time(s)";
	  t->SetTextColor(32); 
	  t->DrawLatex(2.,82.,errore.str().c_str());
	}
	if (j == 18) {
	  errore.str("");
	  errore << "Problems with coding: " << ver[i][j];
	  errore << " time(s)";
	  t->DrawLatex(2.,18.,errore.str().c_str());
	  check = true;
	}
	if (j == 19) {
	  errore.str("");
	  errore << "Pedestal checksum wrong: " << ver[i][j];
	  errore << " time(s)";
	  t->DrawLatex(2.,14.,errore.str().c_str());
	  check = true;
	}
	if (j == 20) {
	  errore.str("");
	  errore << "Thresholds checksum wrong: " << ver[i][j];
	  errore << " time(s)";
	  t->DrawLatex(2.,10.,errore.str().c_str());
	  check = true;
	}
	if (j == 21) { 
	  errore.str("");
	  errore << "WARNING! DEXYC < 0: " << ver[i][j];
	  errore << " time(s)";
	  t->DrawLatex(2.,6.,errore.str().c_str());
	  check = true;
	}
	if (j == 22) { 
	  errore.str("");
	  errore << "Packet length is zero (YODA input error), skipped: " << ver[i][j];
	  errore << " time(s)";
	  t->DrawLatex(2.,3.,errore.str().c_str());
	  check = true;
	};
      };
    }; 
    t->SetTextColor(50); 
    if ( fulldiff[i] !=0 ) {
      check = true;
      errore.str("");
      errore << "Full mode, differences between RAW and COMPRESS mode: " << fulldiff[i];
      errore << " time(s)";
      t->DrawLatex(2.,46.,errore.str().c_str());
    };
    if ( cpre[i] !=0 ) {
      errore.str("");
      errore << "Preamplifier fully transmitted: " << cpre[i];
      errore << " time(s)";
      t->SetTextColor(32); 
      t->DrawLatex(2.,78.,errore.str().c_str());
    };
  };
  rapporto->cd();
  t->SetTextFont(32);
  t->SetTextColor(1);
  t->SetTextSize(0.05);
  t->SetTextAlign(12);
  t->DrawLatex(22.,95.,"Calorimeter quick look: ");
  //printf("check %i \n",check);
  if ( check ){
    t->SetTextColor(50);
    t->DrawLatex(60.,95.," WARNING, CHECK! ");	
    printf("cdexyc %f cdexy %f ctshit %f cbase %f \n",cdexyc,cdexy,ctshit,cbase);
  } else {
    t->SetTextColor(32);
    t->DrawLatex(60.,95.," OK! ");	
  };
  //
  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;    
  stringstream figsave1;    
  stringstream figsave2;    
  const char *format = saveas;
  if ( !strcmp(format,"ps") ) {
    figsave.str("");
    figsave << outdir << "/" ;
    figsave << figrec << "_qlook.";
    figsave << format << "(";
    rapporto->Print(figsave.str().c_str(),"Landscape");    
    figsave1.str("");
    figsave1 << outdir << "/" ;
    figsave1 << figrec << "_qlook.";
    figsave1 << format;
    figura->Print(figsave1.str().c_str(),"Landscape");
    figsave2.str("");
    figsave2 << outdir << "/" ;
    figsave2 << figrec << "_qlook.";
    figsave2 << format << ")";
    figura2->Print(figsave2.str().c_str(),"Landscape");
  } else {
    figsave.str("");
    figsave << outdir << "/" ;
    figsave << figrec << "_qlook1.";
    figsave << format;
    figura->SaveAs(figsave.str().c_str());
    figsave.str("");
    figsave << outdir << "/" ;
    figsave << figrec << "_qlook2.";
    figsave << format;
    figura2->SaveAs(figsave.str().c_str());
    figsave.str("");
    figsave << outdir << "/" ;
    figsave << figrec << "_qlook3.";
    figsave << format;
    rapporto->SaveAs(figsave.str().c_str());    
  };
}

