#include <TMath.h>
#include <TStyle.h>
#include <TLegend.h>
#include <TPad.h>
#include <TROOT.h>
#include <TError.h>
#include <TSystem.h>
#include <TImage.h>

#include <math.h>

#include <vacoord.h> 

#include <CaryatidAna.h>
#include <sstream>

using namespace std;

CaryatidAna* CaryatidAna::myCaryatidAna = 0;

CVSID("$Id: CaryatidAna.cxx,v 1.3 2006/11/17 17:38:41 asousa Exp $");

//-------------------------------------------------

CaryatidAna* CaryatidAna::InstantiateMe() {
  if(!myCaryatidAna) {
    myCaryatidAna = new CaryatidAna(); 
  }
  return myCaryatidAna;
}

//-------------------------------------------------

CaryatidAna::~CaryatidAna() {

  mySP.clear();

  fReportFile.close();

  delete myCaryatidAna;
}

//-------------------------------------------------

CaryatidAna::CaryatidAna() {

  //cout << "I got to the Constructor... Yeah!!" << endl;

  gTruncType    = 2;
  gSparsFactor  = 5;
  gTruncLimit   = 5;

  gPlotEachPage = false;
  gPlots        = true;
  gQuickPlots   = true; //Basic plots ONLY!!!
  gAllRootFile  = true; //Whether to write all plots in ROOT file 
                        //irrespectively of gQuickPlots 

  gOutputPedestalTable = false;
  gOutputSparsTable    = false;
  gDebugTable          = false;

  gCheckError2 = true;

  gDoOutliersAnalysis = true;

  gComparePedTable  = true;
  gCompareSparTable = true;
  gTolerancePedTable  = 1;
  gToleranceSparTable = 10;
  
  fFile = 0;
  gErrorIgnoreLevel = 1;
  gStyle->SetOptStat(111111);
  gStyle->SetPalette(1);

  //Counter of exceptions to error=2 for pedestal data:
  ferrorNot2 = 0;
}

//-------------------------------------------------

void CaryatidAna::DoOnlineAnalysis(Char_t *fileName) {


  //
  // Configure CaryatidAna options:
  //
  this->gOutputSparsTable    = true;
  this->gOutputPedestalTable = false;
  this->gComparePedTable     = false;
  this->gCompareSparTable    = true;
  this->gCheckError2         = false; 
  this->gDoOutliersAnalysis  = true;
  this->gPlots               = true;
  this->gQuickPlots          = true;
  this->gAllRootFile         = true;
  this->gFileName            = fileName;
  this->gToleranceSparTable  = 5;
  
  //Truncation options:
  this->gTruncType   = 2; //1=(based on raw sigma) & 2=(studied fixed values)
  this->gTruncLimit  = 5; //Truncation level (for method 1 only)
  this->gSparsFactor = 5; //Number of sigmas for sparsification threshold
  
  //Execute function to get Caryatid analysis:
  MSG("CaryatidAna",Msg::kInfo) << "\tInitialising analysis variables..." << endl;
  this->InitAnaVariables();


  MSG("CaryatidAna",Msg::kInfo) << "\tAnalysis starts here...\n\n\tGetting MEANs and RMSs..." << endl;
  this->ProcessCaryatids();

  if(gOutputPedestalTable || gOutputSparsTable) {
    MSG("CaryatidAna",Msg::kInfo) << "\tOutputing Caryatid Tables (a la online)..." << endl;
  this->OutputTables();
  }

  if(gCompareSparTable) {
      MSG("CaryatidAna",Msg::kInfo) << "\tComparing Caryatids and previous DAQ Tables..." << endl;
      this->LoadDAQTrees();
      this->CompareDAQTables();
      delete fSparDAQTree;
     
  }



  MSG("CaryatidAna",Msg::kInfo) << "\tEt voila! Plotting at last...\n" << endl;
  if(this->gPlots) this->GetPlots();

  return;
}

//-------------------------------------------------

void CaryatidAna::DoOfflineAnalysis(const Int_t entriesMax) {

  //Configure Caryatids:
  Caryatid::SetTruncFlag(gTruncType);
  Caryatid::SetTruncFactor(gTruncLimit);
  Caryatid::SetSparsFactor(gSparsFactor);
  //Do not do quick plots:
  this->gQuickPlots = true;
  this->gAllRootFile = true;

  MSG("CaryatidAna",Msg::kInfo) << "\tGetting Caryatid TTrees..." << endl;
  Int_t success = this->LoadPedTree();
  if(!success) {
    MSG("CaryatidAna",Msg::kError) << "ERROR: Input TTree could not be loaded." << endl;
    return;
  }
  //Get the pedestals from the CaryatidReco TTree:
  MSG("CaryatidAna",Msg::kInfo) << "\tGetting data from Caryatid TTrees..." << endl;
  Int_t SPcounter = this->GetSPData(entriesMax);
  MSG("CaryatidAna",Msg::kInfo) << "\t\tGot "<< SPcounter << " Caryatids! " << endl;

  MSG("CaryatidAna",Msg::kInfo) << "\tInitialising analysis variables..." << endl;
  this->InitAnaVariables();

  MSG("CaryatidAna",Msg::kInfo) << "\tAnalysis starts...\n\n\tGetting MEANs and RMSs..." << endl;
  this->ProcessCaryatids();

  delete fPedRawTree;

  if(gCompareSparTable || gComparePedTable) {
    MSG("CaryatidAna",Msg::kInfo) << "\tComparing Caryatids and previous DAQ Tables..." << endl;
    this->LoadDAQTrees();
    this->CompareDAQTables();
  }

  delete fPedDAQTree;
  delete fSparDAQTree;

  //Output Tables into files (crate-wise):
  if(gOutputPedestalTable || gOutputSparsTable) {
    MSG("CaryatidAna",Msg::kInfo) << "\tOutputting a la online Tables..." << endl;
    this->OutputTables();
  }

  //MSG("CaryatidAna",Msg::kInfo) << "\tReporting..." << endl;
  //this->Report();

  MSG("CaryatidAna",Msg::kInfo) << "\tEt voila! Plotting at last...\n" << endl;
  if(gPlots) this->GetPlots();
}

//-------------------------------------------------

Bool_t CaryatidAna::LoadPedTree() {

  fFile = TFile::Open(gFileName.c_str());
  fPedRawTree = (TTree*) fFile->Get("CaryatidTree");
  
  fPedRawTree->SetBranchAddress("run",  &frun);
  fPedRawTree->SetBranchAddress("error",&ferror);
  fPedRawTree->SetBranchAddress("crate",&fcrate);
  fPedRawTree->SetBranchAddress("varc", &fvarc);
  fPedRawTree->SetBranchAddress("vmm",  &fvmm);
  fPedRawTree->SetBranchAddress("vfb",  &fvfb);
  fPedRawTree->SetBranchAddress("va",   &fva);
  fPedRawTree->SetBranchAddress("vach", &fvach);
  fPedRawTree->SetBranchAddress("adc",  &fadc);
  //fPedRawTree->SetBranchAddress("tdc",  &ftdc);
  fPedRawTree->SetBranchAddress("plane",&fplane);
  fPedRawTree->SetBranchAddress("tUTC", &ftUTC);

  return true;
}


//-------------------------------------------------

void  CaryatidAna::CreateReportFile() {
 
  string fileName = "CaryatidReport_";
  fileName += Form("%i",frun);

  fReportFile.open(fileName.c_str(),ofstream::out | ofstream::app);

  return;
}

//-------------------------------------------------

Bool_t CaryatidAna::LoadDAQTrees() {

  TFile* fFile = TFile::Open(gFileName.c_str()); 
  fPedDAQTree = (TTree*) fFile->Get("pedTableTree");
  
  fPedDAQTree->SetBranchAddress("crate",&pedcrate);
  fPedDAQTree->SetBranchAddress("varc", &pedvarc);
  fPedDAQTree->SetBranchAddress("vmm",  &pedvmm);
  fPedDAQTree->SetBranchAddress("vfb",  &pedvfb);
  fPedDAQTree->SetBranchAddress("va",   &pedva);
  fPedDAQTree->SetBranchAddress("vach", &pedvach);
  fPedDAQTree->SetBranchAddress("adc",  &pedadc);
  //fPedDAQTree->SetBranchAddress("time", &pedLoadTime);

  fSparDAQTree = (TTree*) fFile->Get("sparTableTree");
  
  fSparDAQTree->SetBranchAddress("crate",&sparcrate);
  fSparDAQTree->SetBranchAddress("varc", &sparvarc);
  fSparDAQTree->SetBranchAddress("vmm",  &sparvmm);
  fSparDAQTree->SetBranchAddress("vfb",  &sparvfb);
  fSparDAQTree->SetBranchAddress("va",   &sparva);
  fSparDAQTree->SetBranchAddress("vach", &sparvach);
  fSparDAQTree->SetBranchAddress("adc",  &sparadc);
  //fSparDAQTree->SetBranchAddress("time", &sparLoadTime);
 
  return true;
}

//-------------------------------------------------

void CaryatidAna::ReportThisGuy() {

  //MSG("CaryatidAna",Msg::kInfo) 
  fReportFile << "\t@: " << fvarc << "-" << fvmm << "-" 
	      << fvfb << "-" << fva << "-" << fvach
	      << "\t"
	      << "(Error: " << ferror << "  ADC: " << fadc 
	      << "  Time: " << ftdc << ")" 
	      << endl << endl;

  return;
}

//-------------------------------------------------

void CaryatidAna::CheckDataQuality() {

  //Pedestal Data has ALWAYS error=2 associated
  if(gCheckError2 && ferror!=2) {
    fReportFile << "\tFound entry with errro!=2.(" << "Exception #: " << ferrorNot2 << ")." << endl;
    this->ReportThisGuy();
    ferrorNot2++;
  }

  //Too high/low pedestal values:
  if(fadc < ADCMIN || fadc > ADCMAX) {
    fReportFile << "\tFound pedestal with ADC too high/low" << endl;
    this->ReportThisGuy();
  }

  return;
}

//-------------------------------------------------

Int_t CaryatidAna::GetSPData(const Int_t entriesMax) {

  Int_t nentries = 0;

  //LOOP over the Caryatid TTree.
  if (entriesMax == -1)  nentries = Int_t(fPedRawTree->GetEntries());
  else nentries = entriesMax;

  for (Int_t jentry=0; jentry<nentries;jentry++) {
    fPedRawTree->GetEvent(jentry);

    this->CheckDataQuality();
	 
    Int_t key = Caryatid::EncriptMeAKey(fcrate,fvarc,fvmm,fvfb,fva,fvach);

    //If it does not found (i.e. iter points to end) -> then create it:
    if( mySP.find(key) == mySP.end() ) mySP[key] = new Caryatid();

    mySP[key]->AddressMe(fcrate,fvarc,fvmm,fvfb,fva,fvach);
    //mySP[key]->SetTime(ftUTC);
    mySP[key]->SetPlane(fplane);
    mySP[key]->SetError(ferror);
    mySP[key]->InputSPEntry(fadc);
  }

  return mySP.size();

}

//-------------------------------------------------

void CaryatidAna::ProcessCaryatids() {

  //Iterate over the entries in the vector:
  map<Int_t,Caryatid*>::iterator iterSP = mySP.begin();

  while(iterSP != mySP.end()) {


    //Process all the MEANs and RMSs - for each Caryatid at the time:
    iterSP->second->GetSTAT();

    //Clears off the arrays of each Caryatid - free up memory.
    iterSP->second->FlushCaryatids();

    if( (iterSP->second->SparsifiedChannel()) ) {
      iterSP++;
      continue;
    }

    MSG("CaryatidAna", Msg::kDebug) << iterSP->second->GetCrate() 
                                    << "-" 
                                    << iterSP->second->GetVarc()  
                                    << "-" 
                                    << iterSP->second->GetVmm() 
                                    << "-" 
                                    << iterSP->second->GetVfb()
                                    << "-" 
                                    << iterSP->second->GetVA()
                                    << "-" 
                                    << iterSP->second->GetVAch()
                                    << endl 
                                    << iterSP->second->GetRawMean() 
                                    << endl
                                    << iterSP->second->GetRawRms() 
                                    << endl
                                    << iterSP->second->GetEntries() 
                                    << endl
                                    << iterSP->second->GetRmsT2() 
                                    << endl
                                    << iterSP->second->GetEntriesT2() 
                                    << endl
                                    << iterSP->second->GetSparsLevelT2() 
                                    << endl
                                    << endl;

    //MEAN distribution
    fMeanRaw_h->Fill((iterSP->second->GetRawMean()));

    switch(gTruncType) { 
    case 1:
      fMeanT1_h->Fill((iterSP->second->GetMeanT1()));
      break;
    case 2:
      fMeanT2_h->Fill( (iterSP->second->GetMeanT2()) );
      break;
    }

    //RMS ALL channels
    fRmsRaw_h->Fill((iterSP->second->GetRawRms()));

    //Sparsification Threshold without truncation: 
    fSparcRaw_h->Fill( (iterSP->second->GetRawSparsLevel()) );

    switch(gTruncType) { 
    case 1:
      fRmsT1_h->Fill((iterSP->second->GetRmsT1()));
      break;
    case 2:
      fRmsT2_h->Fill((iterSP->second->GetRmsT2()));
      break;
    }

    //RMS distribution for the different readout types in FEE @ FD:
    if( (iterSP->second->IsLGPIN()) ) {
      //LG PIN CHANNELs - no truncation:
      fRmsRawPINLG_h->Fill((iterSP->second->GetRawRms()));
      switch(gTruncType) { 
      case 1:
	//LG PIN CHANNELs - truncated:
	fRmsPINLG_h->Fill((iterSP->second->GetRmsT1()));
	//Sparsification thrshold:
	fSparcLGPIN_h->Fill((iterSP->second->GetSparsLevelT1()));
	break;
      case 2:
	//LG PIN CHANNELs - truncated:
	fRmsPINLG_h->Fill((iterSP->second->GetRmsT2()));
	//Sparsification thrshold:
	fSparcLGPIN_h->Fill((iterSP->second->GetSparsLevelT2()));
	break;
      }
    }
    else if( (iterSP->second->IsHGPIN()) ) {
      //HG PIN CHANNELs:
      fRmsRawPINHG_h->Fill((iterSP->second->GetRawRms()));
      switch(gTruncType) {
      case 1:
	//HG PIN CHANNELs - truncated:
	fRmsPINHG_h->Fill((iterSP->second->GetRmsT1()));
	//Sparsification thrshold:
	fSparcHGPIN_h->Fill((iterSP->second->GetSparsLevelT1()));
	break;
      case 2:
	//HG PIN CHANNELs - truncated:
	fRmsPINHG_h->Fill((iterSP->second->GetRmsT2()));
	//Sparsification thrshold:
	fSparcHGPIN_h->Fill((iterSP->second->GetSparsLevelT2()));
	break;
      }
    }
    else if( (iterSP->second->IsCMchannel()) )  {
      //CM CHANNELs:
      fRmsRawCM_h->Fill( (iterSP->second->GetRawRms()) );
      switch(gTruncType) {
      case 1:
	fRmsCM_h->Fill((iterSP->second->GetRmsT1()));
	break;
      case 2:
	fRmsCM_h->Fill((iterSP->second->GetRmsT2()));
	break;
      }
    }
    else {
      //PMT CHANNELs:
      //Raw RMS distribution:
      fRmsRawPMT_h->Fill( (iterSP->second->GetRawRms()) );

      switch(gTruncType) { 
      case 1:
	fRmsPMT_h->Fill( (iterSP->second->GetRmsT1()) );
	//Sparsification threshold:
	fSparc_h->Fill( (iterSP->second->GetSparsLevelT1()) );
	break;
      case 2:
	fRmsPMT_h->Fill( (iterSP->second->GetRmsT2()) );
	//Sparsification threshold:
	fSparc_h->Fill( (iterSP->second->GetSparsLevelT2()) );
	break;
      }
    }

    const Int_t icrate = iterSP->second->GetCrate();
    const Int_t ivarc = iterSP->second->GetVarc();
    const Int_t ivmm  = iterSP->second->GetVmm();
    const Int_t ivfb  = iterSP->second->GetVfb();
    const Int_t iva   = iterSP->second->GetVA();
    const Int_t ivach = iterSP->second->GetVAch();

    //Mapping of MEAN and RMS per each channel:
    fMeanMap_h->Fill(6*3*2*icrate+6*2*ivarc+2*ivmm+ivfb, 
		     30*iva+ivach,
		     (iterSP->second->GetRawMean()) );
    fRmsMap_h->Fill(6*3*2*icrate+6*2*ivarc+2*ivmm+ivfb,  
		    30*iva+ivach,
		    (iterSP->second->GetRawRms()) );

    fEntriesMap_h->Fill(6*3*2*icrate+6*2*ivarc+2*ivmm+ivfb,
			30*iva+ivach, 
			(iterSP->second->GetEntries()) );

    
    //Fill OM style maps
    Int_t xc=0;
    Int_t yc=0;

    Int_t co=vacoord(ivach);

    xc=co%6;
    yc=(co-xc)/6;

    Int_t xc01=ivarc*3*6+iva*6+xc+1+(icrate%4)*9*6;
    Int_t yc01=ivmm*2*6+ivfb*6+yc+1+(3-icrate/4)*72;

    fvarcevent[0]->SetBinContent(xc01, yc01, (iterSP->second->GetRawMean()) );

    fvarcevent[2]->SetBinContent(xc01, yc01, (iterSP->second->GetRawRms()) );

    fvarcevent[5]->SetBinContent(xc01, yc01, (iterSP->second->GetEntries()) );

  
    //Mapping with truncation:
    switch(gTruncType) { 
    case 1:
      fRmsMapT_h->Fill(6*3*2*icrate+6*2*ivarc+2*ivmm+ivfb,  
		       30*iva+ivach, 
		       (iterSP->second->GetRmsT1()) );
      //Truncated - nonTruncated values:
      fDeltaMeanMapT_h->Fill(6*3*2*icrate+6*2*ivarc+2*ivmm+ivfb, 
			     30*iva+ivach, 
			     TMath::Abs(iterSP->second->GetRawMean()-iterSP->second->GetMeanT1()) );

      fDeltaRmsMapT_h->Fill(6*3*2*icrate+6*2*ivarc+2*ivmm+ivfb,  
			    30*iva+ivach, 
			    (iterSP->second->GetRawRms())-(iterSP->second->GetRmsT1()));
      
      fSparcMap_h->Fill(6*3*2*icrate+6*2*ivarc+2*ivmm+ivfb,  
			30*iva+ivach, 
			(iterSP->second->GetSparsLevelT1()) );

      fvarcevent[3]->SetBinContent(xc01, yc01, (iterSP->second->GetRmsT1()) );
      
      fvarcevent[1]->SetBinContent(xc01, yc01,TMath::Abs(iterSP->second->GetRawMean()-iterSP->second->GetMeanT1()));
      
      fvarcevent[4]->SetBinContent(xc01, yc01, ((iterSP->second->GetRawRms())-(iterSP->second->GetRmsT1())));
      
      fvarcevent[7]->SetBinContent(xc01, yc01, (iterSP->second->GetSparsLevelT1()) );
      break;
    case 2:
      fRmsMapT_h->Fill(6*3*2*icrate+6*2*ivarc+2*ivmm+ivfb,  
		       30*iva+ivach, 
		       (iterSP->second->GetRmsT2()) );
      //Truncated - nonTruncated values:
      fDeltaMeanMapT_h->Fill(6*3*2*icrate+6*2*ivarc+2*ivmm+ivfb, 
			     30*iva+ivach, 
			     TMath::Abs(iterSP->second->GetRawMean()-iterSP->second->GetMeanT2()) );

      fDeltaRmsMapT_h->Fill(6*3*2*icrate+6*2*ivarc+2*ivmm+ivfb,  
			    30*iva+ivach, 
			    (iterSP->second->GetRawRms())-(iterSP->second->GetRmsT2()) );
      
      fSparcMap_h->Fill(6*3*2*icrate+6*2*ivarc+2*ivmm+ivfb,  
			30*iva+ivach, 
			(iterSP->second->GetSparsLevelT2()));
     
      fvarcevent[3]->SetBinContent(xc01, yc01, (iterSP->second->GetRmsT2()) );

      fvarcevent[1]->SetBinContent(xc01, yc01, 
                                   TMath::Abs(iterSP->second->GetRawMean()-iterSP->second->GetMeanT2()));

      fvarcevent[4]->SetBinContent(xc01, yc01, ((iterSP->second->GetRawRms())-(iterSP->second->GetRmsT2())));
      
      fvarcevent[7]->SetBinContent(xc01, yc01, (iterSP->second->GetSparsLevelT2()) );
      
      break;
    }

    //cout << iterSP->second->GetError() << endl;
    fErrorMap_h->Fill(6*3*2*icrate+6*2*ivarc+2*ivmm+ivfb,  
		      30*iva+ivach, 
		      iterSP->second->GetError());

    fvarcevent[6]->SetBinContent(xc01, yc01, (iterSP->second->GetError()) );
      
    //OUTLIERS analysis:
    if(gDoOutliersAnalysis) {

      const Int_t iplane = iterSP->second->GetPlane();

      Int_t outliersNum = 0;
      
      switch(gTruncType) { 
      case 1:
	outliersNum = iterSP->second->GetEntries()-iterSP->second->GetEntriesT1();
	break;  
      case 2:
	outliersNum = iterSP->second->GetEntries()-iterSP->second->GetEntriesT2();
      break;
      }
      
      //Multiplicity of outliers per channel:
      fPerTrunc_h->Fill(outliersNum);

      
      //Map of outliers in FEE space:
      fOutMap_h->Fill(6*3*2*icrate+6*2*ivarc+2*ivmm+ivfb,  
		      30*iva+ivach, 
		      outliersNum);
      
      fvarcevent[8]->SetBinContent(xc01, yc01, outliersNum); //OM style map
      
      //Plane occupancy
      fOutDetMap_h->Fill(iplane,outliersNum);
      
      //VA channels occupancy:
      fTruncOccVA_h->Fill(ivach,outliersNum);
      
      //Crate occupancy:
      fTruncOccCM_h->Fill(icrate,outliersNum);
      
      //Spectra of Outliers (not yet implemented)
     }
    iterSP++;
  }
  return;
}

//-------------------------------------------------

void CaryatidAna::OutputTables() {

  //Loop over the crates (because of one file per crate)
  for(Int_t icrate = 0; icrate < Caryatid::CRATEMAX; icrate++) {
    
    ofstream sparFile;
    ofstream pedFile;

    if(gOutputSparsTable) {	      
      string sparFileName = "recentSparsifierTable_rop";
      sparFileName += Form("%i",icrate);
      //sparFileName += "_byCaryatid";

      sparFile.open(sparFileName.c_str(),ofstream::out );
    }


    if(gOutputPedestalTable) {	      
      string pedFileName = "recentPedTable_rop";
      pedFileName += Form("%i",icrate);
      //pedFileName += "_byCaryatid";
      
      pedFile.open(pedFileName.c_str(),ofstream::out );
    }

    Int_t sparThreshold = -1;
    Int_t pedThreshold  = -1;

    for(Int_t ivarc = 0; ivarc < Caryatid::VARCMAX; ivarc++) { 
      for(Int_t ivmm = 0; ivmm < Caryatid::VMMMAX; ivmm++) { 
	for(Int_t ivfb = 0; ivfb < Caryatid::VFBMAX; ivfb++) {
	  for(Int_t iva = 0; iva < Caryatid::VAMAX; iva++) {
	    for(Int_t ivach = 0; ivach < Caryatid::VACHMAX; ivach++) {
    
	      
	      Int_t key = Caryatid::EncriptMeAKey(icrate,
						      ivarc,
						      ivmm,
						      ivfb,
						      iva,
						      ivach);

	      //Some physical FEE location have no electronics connected (null Caryatids):
	      if( mySP.find(key) == mySP.end() ) {
		//if(mySP.find(key) ) {
		MSG("CaryatidAna",Msg::kDebug) << "Empty Entry at:"
					      << icrate
					      << "-"
					      << ivarc
					      << "-"
					      << ivmm
					      << "-"
					      << ivfb
					      << "-"
					      << iva
					      << "-"
					      << ivach
					      << endl;
		
		//Not connected electronic, hence:
		sparThreshold = 16383;
		pedThreshold  = 1;
	      }
	      else {
		switch(gTruncType) {
		case 1:
		  sparThreshold = (Int_t) mySP[key]->GetSparsLevelT1();
		  break;
		case 2:
		  sparThreshold = (Int_t) mySP[key]->GetSparsLevelT2();
		  break;
		}
		
		if(mySP[key]->IsTPMTchannel()) sparThreshold = this->GetTPMTsparTh();
		
		//(*,*,*,*,*,0) && (*,*,*,*,2,18) || (*,*,*,*,*,1,19,20,21)
		if(mySP[key]->SparsifiedChannel() 
		   ||
		   mySP[key]->IsCMchannel()) {
		  
		  sparThreshold = 16383;
		  pedThreshold = (Int_t) mySP[key]->GetRawMean(); 
		}
	      }
	      
	      //Sparsification Table stuff:		  
	      if(gOutputSparsTable) {	      
		if(gDebugTable && ivach==0) sparFile << icrate << "_"
						     << ivarc  <<"_"
						     << ivmm   <<"_"
						     << ivfb   <<"_"
						     << iva    <<">> ";
		
		//sparFile << " " << (Int_t) (sparThreshold);
		sparFile << (Int_t) (sparThreshold) << " ";
		if(ivach == 21) sparFile << endl;
	      }

	      //Pedestal Table stuff:
	      if(gOutputPedestalTable) {
		if(gDebugTable && ivach==0) pedFile << icrate << "_"
						    << ivarc  <<"_"
						    << ivmm   <<"_"
						    << ivfb   <<"_"
						    << iva    <<">> ";

		pedFile << pedThreshold << " " ;
		if(ivach == 21) pedFile << endl;
	      }
	    }
	  }
	}
      }
    }
    
    if(gOutputSparsTable) sparFile.close();
    if(gOutputPedestalTable) pedFile.close();
  }
  return;
}

//-------------------------------------------------

void CaryatidAna::CompareDAQTables() {
    
    if(gComparePedTable) {
        for(Int_t ientry = 0; ientry < fPedDAQTree->GetEntries(); ientry++) {
            Int_t suc = fPedDAQTree->GetEvent(ientry);
            if(suc<0) {
                MSG("CaryatidAna",Msg::kInfo) << "Failed: " << suc 
                                              << "\t" << ientry << endl;
                continue;
            }
            
            Int_t key = Caryatid::EncriptMeAKey(pedcrate,
                                                pedvarc,
                                                pedvmm,
                                                pedvfb,
                                                pedva,
                                                pedvach );
            Int_t pedSP = -1;
            
            if(mySP[key]) pedSP = (Int_t)mySP[key]->GetRawMean();
            else pedSP = 1;
            
            MSG("CaryatidAna",Msg::kInfo) << "PedComp: " 
                                          << pedSP
                                          << "-"
                                          << pedadc
                                          << "-"
                                          << pedSP - pedadc
                                          << endl;
            
            fDeltaMean_h->Fill(Int_t(pedSP - pedadc));
            
            fDeltaCompMean_h->Fill(6*3*2*pedcrate+6*2*pedvarc+2*pedvmm+pedvfb,
                                   30*pedva+pedvach,
                                   Int_t(pedSP - pedadc));
            
            //If discrepancies-> Report it:
            if(pedadc>1 
               &&
               //mySP[key]->GetRawMean()> 0 
               //&& 
               TMath::Abs(pedSP-pedadc)>gTolerancePedTable) {
                
                fReportFile << "\tDiscrepancy between pedestal values > " 
                            << gTolerancePedTable 
                            << " ADCs." << endl
                            << "\t\tmyPed-tablePed ("
                            << pedSP << "-" << pedadc <<") =\t"
                            << pedSP - pedadc 
                            << " @ " 
                            << pedcrate <<"_" 
                            << pedvarc  <<"_" 
                            << pedvmm   <<"_"
                            << pedvfb   <<"_"
                            << pedva    <<"_"
                            << pedvach  << endl;
            }
        }
    }
    
    if(gCompareSparTable) {
        for(Int_t ientry = 0; ientry < fSparDAQTree->GetEntries(); ientry++) {
            Int_t suc = fSparDAQTree->GetEvent(ientry);
            if(suc<0) {
                MSG("CaryatidAna",Msg::kInfo) << "Failed: " << suc 
                                              << "\t" << ientry << endl;
                continue;
            }
            
            Int_t key = Caryatid::EncriptMeAKey(sparcrate,
                                                sparvarc,
                                                sparvmm,
                                                sparvfb,
                                                sparva,
                                                sparvach );
            Int_t sparThreshold = -1;
            Float_t rms = -1;
            if( mySP.find(key) == mySP.end() ) {
                //if(!mySP[key]) {
                sparThreshold = 16383;
                rms = 0.5;
            }
            else {
                //TPMT channel:
                if(mySP[key]->IsTPMTchannel()) {
                    sparThreshold = this->GetTPMTsparTh();
                    rms = 0.5;
                }
                //(*,*,*,*,*,0) && (*,*,*,*,2,18) || (*,*,*,*,*,1,19,20,21)
                else if(mySP[key]->SparsifiedChannel() 
                        ||
                        mySP[key]->IsCMchannel()) {
                    sparThreshold = 16383;
                    rms = 0.5;
                }
                //PMT channel:
                else {
                    switch(gTruncType) { 
                    case 1:
                        sparThreshold = (Int_t) mySP[key]->GetSparsLevelT1();
                        rms = mySP[key]->GetRawRms();
                        break;
                    case 2:
                        sparThreshold = (Int_t) mySP[key]->GetSparsLevelT2();
                        rms = mySP[key]->GetRawRms();
                        break;
                    }
                }
            }
            
            MSG("CaryatidAna",Msg::kDebug) << "SparComp: " 
                                           << sparThreshold
                                           << "-"
                                           << sparadc
                                           << "-"
                                           << sparThreshold - sparadc
                                           << endl;
            
            if(TMath::Abs(sparThreshold - sparadc) < 15000) {
                
                fDeltaSparc_h->Fill(Int_t(sparThreshold-sparadc));
              
                fDeltaSparcMap_h->Fill(6*3*2*sparcrate+6*2*sparvarc+2
                                       *sparvmm+sparvfb,
                                       30*sparva+sparvach,
                                       static_cast<Int_t>
                                       (sparThreshold-sparadc));
                
                //Now fill OM style maps
                Int_t xc=0;
                Int_t yc=0;
                
                Int_t co=vacoord(sparvach);
                
                xc=co%6;
                yc=(co-xc)/6;
                
                Int_t xc01=sparvarc*3*6+sparva*6+xc+1+(sparcrate%4)*9*6;
                Int_t yc01=sparvmm*2*6+sparvfb*6+yc+1+(3-sparcrate/4)*72;
                
                if(TMath::Abs(sparThreshold - sparadc) > gToleranceSparTable) {
                    
                    fvarcevent[9]->SetBinContent(xc01, yc01, 
                                                 TMath::Abs(static_cast<Int_t>
                                                 (sparThreshold-sparadc)));
                }
                
                if( rms > 0 && 
                    TMath::Abs(sparThreshold - sparadc) 
                    > gToleranceSparTable) {
                    
                    fReportFile << "\tDiscrepancy between sparsification" 
                                << "thresholds values > " 
                                << gToleranceSparTable
                                << " ADCs." << endl
                                << "\t\tmySparTh-tableSparTh ("
                                << sparThreshold << "-" << sparadc <<") =\t" 
                                << sparThreshold - sparadc
                                << " @ " 
                                << sparcrate <<"_" 
                                << sparvarc <<"_" 
                                << sparvmm  <<"_"
                                << sparvfb  <<"_"
                                << sparva   <<"_"
                                << sparvach  << endl;
                }	
            }
            //else cout << "found one!" << endl;
        }
    }
    return;
}


//-------------------------------------------------

void CaryatidAna::Report() {

  fReportFile << endl 
	      << "Sparsification Thresholds Summaries: " 
	      << endl
	      << endl
	      << "\tFor PMTs truncated: "     << fSparc_h->GetMean()      
	      << "+/_" << fSparc_h->GetRMS()      << endl
    
	      << "\tFor PMTs non-truncated: " << fSparcRaw_h->GetMean()   
	      << "+/_" << fSparcRaw_h->GetRMS()   << endl
    
	      << "\tFor LG PIN truncated: "   << fSparcLGPIN_h->GetMean() 
	      << "+/_" << fSparcLGPIN_h->GetRMS() << endl
    
	      << "\tFor HG PIN truncated: "   << fSparcHGPIN_h->GetMean() 
	      << "+/_" << fSparcHGPIN_h->GetRMS() << endl
	      << endl;

  return;
}

//-------------------------------------------------

void CaryatidAna::GetPlots() {

  //Drawing in File:
  fplotFile_c = new TCanvas("plotFile_c","",1200,800);
  TLegend* leg = new TLegend(0.4,0.6,0.89,0.89);

  Int_t plotCounter = 1;
  Int_t plotCounterRoot = 1;

  string bookName = "CaryatidPlots_";
  bookName += Form("t%i_s%i_%i.ps",gTruncType,gSparsFactor,frun);

  string bookNameStart = bookName + "(";
  string bookNameEnd   = bookName + ")";

  //For output ROOT file
  string bookNameR = "CaryatidPlots_";
  bookNameR += Form("t%i_s%i_%i.root",gTruncType,gSparsFactor,frun);
  TFile *outp;
  outp=new TFile(bookNameR.c_str(),"RECREATE");

  string plotNameEps;
  string plotNameGif;
  string plotNameR;

  //Create directory
  if(gPlotEachPage) {
    plotNameGif = gSystem->pwd();
    plotNameGif += "CaryatidPlotsAll_";
    plotNameGif += Form("%i/",frun);

    MSG("CaryatidAna",Msg::kInfo) << "Plots will be @ " << plotNameGif.c_str() << endl;

    plotNameEps = plotNameGif;

    Int_t suc = gSystem->MakeDirectory( plotNameGif.c_str() );

    if(suc==-1) {
      MSG("CaryatidAna",Msg::kError) << endl << "ERROR: Directory could not be created" << endl << endl;
      gPlotEachPage = false;
    }
  }
 

  //Means
  fplotFile_c->cd();
  gPad->SetLogy(0);
  fMeanRaw_h->SetXTitle("Pedestal Means [ADC]");
  fMeanRaw_h->Draw();
  fplotFile_c->Update();
  fplotFile_c->Print(bookNameStart.c_str());
  if(gPlotEachPage) {
    plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);    
    plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);

    fplotFile_c->Print(plotNameGif.c_str());
    fplotFile_c->Print(plotNameEps.c_str());
  }
  MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
  plotCounter++;
  
  //Writing canvas to ROOT file
  outp->cd();
  plotNameR = Form("SPplotAtPage%i",plotCounterRoot);    
  fplotFile_c->SetName(plotNameR.c_str());
  fplotFile_c->Write();

  fplotFile_c->Clear();
  plotCounterRoot++;
  

  if(!gQuickPlots || gAllRootFile) {
    //RMS: truncation vs no truncation:
    fplotFile_c->cd();
    gPad->SetLogy(1);
    fRmsRaw_h->SetXTitle("Pedestal RMSs [ADC]");
    fRmsRaw_h->Draw();
    switch(gTruncType) {
    case 1:
      fRmsT1_h->SetLineColor(4);
      fRmsT1_h->Draw("same");
      break;
    case 2:
      fRmsT2_h->SetLineColor(4);
      fRmsT2_h->Draw("same");
      break;
    }
    fplotFile_c->Update();
    if(!gQuickPlots){
        fplotFile_c->Print(bookName.c_str());
        if(gPlotEachPage) {
            plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
            plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
            
            fplotFile_c->Print(plotNameGif.c_str());
            fplotFile_c->Print(plotNameEps.c_str());
        }
        MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
        plotCounter++;
    }
    outp->cd();
    plotNameR = Form("SPplotAtPage%i",plotCounterRoot);    
    fplotFile_c->SetName(plotNameR.c_str());
    fplotFile_c->Write();

    fplotFile_c->Clear();
    plotCounterRoot++;

  }//if(!gQuickPlots)

  
  //non-truncated RMS - populations:
  fplotFile_c->cd();
  gPad->SetLogy(1);
  fRmsRaw_h->SetStats(0);
  fRmsRaw_h->SetXTitle("Non-truncated Pedestal RMSs [ADC]");
  fRmsRaw_h->SetLineColor(1);
  fRmsRaw_h->Draw();
  fRmsRawPMT_h->SetLineColor(4);
  fRmsRawPMT_h->Draw("same");
  fRmsRawCM_h->SetLineColor(3);
  fRmsRawCM_h->Draw("same");
  fRmsRawPINLG_h->SetLineColor(6);
  fRmsRawPINLG_h->Draw("same");
  fRmsRawPINHG_h->SetLineColor(15);
  fRmsRawPINHG_h->Draw("same");
  leg->AddEntry(fRmsRaw_h,"All Channels","l");
  leg->AddEntry(fRmsRawPMT_h,"PMT Channels","l");
  leg->AddEntry(fRmsRawPINHG_h,"HIGH GAIN PINs","l");
  leg->AddEntry(fRmsRawPINLG_h,"LOW GAIN PINs","l");
  leg->AddEntry(fRmsRawCM_h,"CM Channels","l");
  //leg->SetHeader("The Legend Title");
  leg->Draw("same");
  fplotFile_c->Update();
  fplotFile_c->Print(bookName.c_str());
  if(gPlotEachPage) {
    plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
    plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
    
    fplotFile_c->Print(plotNameGif.c_str());
    fplotFile_c->Print(plotNameEps.c_str());
  }
  MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
  plotCounter++;
  
  outp->cd();
  plotNameR = Form("SPplotAtPage%i",plotCounterRoot);    
  fplotFile_c->SetName(plotNameR.c_str());
  fplotFile_c->Write();
  
  fplotFile_c->Clear();
  plotCounterRoot++;
  
  //truncated RMS - populations:
  fplotFile_c->cd();
  gPad->SetLogy(1);
  switch (gTruncType) {
  case 1: 
    fRmsT1_h->SetXTitle("Truncated Pedestal RMSs [ADC]");
    fRmsT1_h->SetLineColor(1);
    fRmsT1_h->SetStats(0);
    fRmsT1_h->Draw();
    break;
  case 2:
    fRmsT2_h->SetXTitle("Truncated Pedestal RMSs [ADC]");
    fRmsT2_h->SetLineColor(1);
    fRmsT2_h->SetStats(0);
    fRmsT2_h->Draw();
    break;
  }
  fRmsPMT_h->SetLineColor(4);
  fRmsPMT_h->Draw("same");
  fRmsCM_h->SetLineColor(3);
  fRmsCM_h->Draw("same");
  fRmsPINLG_h->SetLineColor(6);
  fRmsPINLG_h->Draw("same");
  fRmsPINHG_h->SetLineColor(15);
  fRmsPINHG_h->Draw("same");
  leg->Clear();
  switch (gTruncType) {
  case 1:
    leg->AddEntry(fRmsT1_h,"All Channels","l");
    break;
  case 2:
    leg->AddEntry(fRmsT2_h,"All Channels","l");
    break;
  }
  leg->AddEntry(fRmsPMT_h,"PMT Channels","l");
  leg->AddEntry(fRmsPINHG_h,"HIGH GAIN PINs","l");
  leg->AddEntry(fRmsPINLG_h,"LOW GAIN PINs","l");
  leg->AddEntry(fRmsCM_h,"CM Channels","l");
  //leg->SetHeader("The Legend Title");
  leg->Draw("same");
  fplotFile_c->Update();
  fplotFile_c->Print(bookName.c_str());
  if(gPlotEachPage) {
    plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
    plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
    
    fplotFile_c->Print(plotNameGif.c_str());
    fplotFile_c->Print(plotNameEps.c_str());
    
  }
  MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
  plotCounter++;

  outp->cd();
  plotNameR = Form("SPplotAtPage%i",plotCounter);    
  fplotFile_c->SetName(plotNameR.c_str());
  fplotFile_c->Write();
  
  fplotFile_c->Clear();
  plotCounterRoot++;
	
  if(!gQuickPlots || gAllRootFile) {
    //PMTs RMSs
    fplotFile_c->cd();
    gPad->SetLogy(1);
    fRmsRawPMT_h->SetXTitle("Truncated Pedestal RMSs [ADC]");
    fRmsRawPMT_h->SetLineColor(1);
    fRmsRawPMT_h->Draw();
    fRmsPMT_h->SetLineColor(4);
    fRmsPMT_h->Draw("sames");
    fplotFile_c->Update();
    if(!gQuickPlots) {
        fplotFile_c->Print(bookName.c_str());
        if(gPlotEachPage) {
            plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);    
            plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
            
            fplotFile_c->Print(plotNameGif.c_str());
            fplotFile_c->Print(plotNameEps.c_str());    
        }
        MSG("CaryatidAna",Msg::kInfo) << "Included Page " 
                                      << plotCounter 
                                      << endl;
        plotCounter++;
    }
    outp->cd();
    plotNameR = Form("SPplotAtPage%i",plotCounterRoot);    
    fplotFile_c->SetName(plotNameR.c_str());
    fplotFile_c->Write();

    fplotFile_c->Clear();
    plotCounterRoot++;
        
    //LG PIN RMSs
    fplotFile_c->cd();
    gPad->SetLogy(0);
    fRmsRawPINLG_h->SetXTitle("Truncated Pedestal RMSs [ADC]");
    fRmsRawPINLG_h->SetLineColor(1);
    fRmsRawPINLG_h->Draw();
    fRmsPINLG_h->SetLineColor(4);
    fRmsPINLG_h->Draw("sames");
    fplotFile_c->Update();
    if(!gQuickPlots) { 
        fplotFile_c->Print(bookName.c_str());
        if(gPlotEachPage) {
            plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);    
            plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
            
            fplotFile_c->Print(plotNameGif.c_str());
            fplotFile_c->Print(plotNameEps.c_str());  
        }
        MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
        plotCounter++;
    }
    outp->cd();
    plotNameR = Form("SPplotAtPage%i",plotCounterRoot);    
    fplotFile_c->SetName(plotNameR.c_str());
    fplotFile_c->Write();

    fplotFile_c->Clear();
    plotCounterRoot++;
   

    //HG PINs RMSs
    fplotFile_c->cd();
    gPad->SetLogy(0);
    fRmsRawPINHG_h->SetXTitle("Truncated Pedestal RMSs [ADC]");
    fRmsRawPINHG_h->SetLineColor(1);
    fRmsRawPINHG_h->Draw();
    fRmsPINHG_h->SetLineColor(4);
    fRmsPINHG_h->Draw("sames");
    fplotFile_c->Update();
    
    if(!gQuickPlots) {
        fplotFile_c->Print(bookName.c_str());
        if(gPlotEachPage) {
            plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);    
            plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
            
            fplotFile_c->Print(plotNameGif.c_str());
            fplotFile_c->Print(plotNameEps.c_str());
        }
        MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
        plotCounter++;
    }

    outp->cd();
    plotNameR = Form("SPplotAtPage%i",plotCounterRoot);    
    fplotFile_c->SetName(plotNameR.c_str());
    fplotFile_c->Write();

    fplotFile_c->Clear();
    plotCounterRoot++;
 

    //CM RMSs
    fplotFile_c->cd();
    gPad->SetLogy(1);
    fRmsRawCM_h->SetXTitle("Truncated Pedestal RMSs [ADC]");
    fRmsRawCM_h->SetLineColor(1);
    fRmsRawCM_h->SetMinimum(.5);
    fRmsRawCM_h->Draw();
    fRmsCM_h->SetLineColor(4);
    fRmsCM_h->Draw("sames");
    fplotFile_c->Update();

    if(!gQuickPlots) {
        fplotFile_c->Print(bookName.c_str());
        if(gPlotEachPage) {
            plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
            plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
            
            fplotFile_c->Print(plotNameGif.c_str());
            fplotFile_c->Print(plotNameEps.c_str());
        }
        MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
        plotCounter++;
    }
    
    outp->cd();
    plotNameR = Form("SPplotAtPage%i",plotCounterRoot);    
    fplotFile_c->SetName(plotNameR.c_str());
    fplotFile_c->Write();

    fplotFile_c->Clear();
    plotCounterRoot++;

    //
    // Maps..
    //


    //Commenting all original Caryatid maps, replaced with OM style ones

    //Map of the pedestals:
//     fplotFile_c->Clear();
//     gPad->SetLogz(0);
//     gPad->SetLogy(0);
//     gPad->SetLogx(0); 
//     fMeanMap_h->SetStats(0);
//     fMeanMap_h->Draw("colz");
//     for(Int_t icrate = 0; icrate < Caryatid::CRATEMAX; icrate++) 
//       for(Int_t ivarc = 0; ivarc < Caryatid::VARCMAX; ivarc++) 
//           fLines[icrate][ivarc]->Draw("same");
//     fplotFile_c->Update();
//     fplotFile_c->Print(bookName.c_str());
//     if(gPlotEachPage) {
//       plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
//       plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);

//       fplotFile_c->Print(plotNameGif.c_str());
//       fplotFile_c->Print(plotNameEps.c_str());
//     }
//     MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
//     plotCounter++;  
//     fplotFile_c->Clear();

    //OM style Pedestal ADC MEAN map
    fplotFile_c->Clear();
    fplotFile_c->cd();
    gPad->SetLogz(0);
    gPad->SetLogy(0);
    gPad->SetLogx(0); 
    fvarcevent[0]->SetStats(0);
    fvarcevent[0]->SetOption("COLZ");
    fvarcevent[0]->Draw();
    
    Int_t pedchn=1;
    if (pedchn==1) {
        for (Int_t i=0;i<36;i++) {fvt[i]->Draw();}
    }
    
    for (Int_t i=0;i<23;i++) {
        f1[i]->Draw();
    }
     
    for (Int_t i=0;i<34;i++) {
        fvline[i]->Draw();
    }
    
    for (Int_t i=0;i<16;i++) {
        fcratenums[i]->Draw();
    }
    
    fplotFile_c->Update();
   
    if(!gQuickPlots) {
        fplotFile_c->Print(bookName.c_str());
        if(gPlotEachPage) {
        plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
        plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
        
        fplotFile_c->Print(plotNameGif.c_str());
        fplotFile_c->Print(plotNameEps.c_str());
        }
        MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
        plotCounter++;
    }
    outp->cd();
    plotNameR = Form("SPplotAtPage%i",plotCounterRoot);    
    fplotFile_c->SetName(plotNameR.c_str());
    fplotFile_c->Write();

    fplotFile_c->Clear();
    plotCounterRoot++;

  }//!gQuickPlots || gAllRootFile
  

  
  //Map of truncation effect on pedestal (pedestalRaw - pedestalTRUNC):
//     fplotFile_c->Clear();
//     gPad->SetLogy(0);
//     gPad->SetLogx(0);
//     gPad->SetLogz(0);
//     fDeltaMeanMapT_h->SetStats(0); 
//     fDeltaMeanMapT_h->SetMinimum(0.0);
//     fDeltaMeanMapT_h->Draw("colz");
//     for(Int_t icrate = 0; icrate < Caryatid::CRATEMAX; icrate++) 
//         for(Int_t ivarc = 0; ivarc < Caryatid::VARCMAX; ivarc++)
//             fLines[icrate][ivarc]->Draw("same");
//     fplotFile_c->Update();
//     fplotFile_c->Print(bookName.c_str());
//     if(gPlotEachPage) {
//         plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
//         plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
        
//         fplotFile_c->Print(plotNameGif.c_str());
//         fplotFile_c->Print(plotNameEps.c_str());
//     }
//     MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
//     plotCounter++;
//     fplotFile_c->Clear();
  
  //OM style MEAN truncation effect map
  fplotFile_c->cd();
  gPad->SetLogz(0);
  gPad->SetLogy(0);
  gPad->SetLogx(0); 
  fvarcevent[1]->SetStats(0);
  fvarcevent[1]->SetOption("COLZ");
  fvarcevent[1]->Draw();

  Int_t pedchn=1;
  pedchn=1;
  if (pedchn==1) {
      for (Int_t i=0;i<36;i++) {fvt[i]->Draw();}
  }
  
  for (Int_t i=0;i<23;i++) {
      f1[i]->Draw();
  }
    
  for (Int_t i=0;i<34;i++) {
      fvline[i]->Draw();
  }
  
  for (Int_t i=0;i<16;i++) {
      fcratenums[i]->Draw();
  }
  
  fplotFile_c->Update();
  fplotFile_c->Print(bookName.c_str());
  if(gPlotEachPage) {
      plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
      plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
      
      fplotFile_c->Print(plotNameGif.c_str());
      fplotFile_c->Print(plotNameEps.c_str());
  }
  MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
  plotCounter++;
  
  outp->cd();
  plotNameR = Form("SPplotAtPage%i",plotCounterRoot);    
  fplotFile_c->SetName(plotNameR.c_str());
  fplotFile_c->Write();
  
  fplotFile_c->Clear();
  plotCounterRoot++;
  
  
  if(!gQuickPlots || gAllRootFile) {
      //Map of RMSs - no truncated:
//       fplotFile_c->Clear();
//       gPad->SetLogy(0);
//       gPad->SetLogx(0);
//       gPad->SetLogz(0);
//       //fRmsMap_h->SetMinimum(.5);
//       fRmsMap_h->SetMaximum(25);
//       fRmsMap_h->SetStats(0);
//       fRmsMap_h->Draw("colz");
//       for(Int_t icrate = 0; icrate < Caryatid::CRATEMAX; icrate++) 
//           for(Int_t ivarc = 0; ivarc < Caryatid::VARCMAX; ivarc++)
//               fLines[icrate][ivarc]->Draw("same");
//       fplotFile_c->Update();
//       fplotFile_c->Print(bookName.c_str());
//       if(gPlotEachPage) {
//           plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
//           plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
          
//           fplotFile_c->Print(plotNameGif.c_str());
//           fplotFile_c->Print(plotNameEps.c_str());
//       }
//       MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
//       plotCounter++;
//       fplotFile_c->Clear();

      //OM style RMS truncated map
      fplotFile_c->cd();
      gPad->SetLogy(0);
      gPad->SetLogx(0);
      gPad->SetLogz(0);
      
      fvarcevent[2]->SetStats(0);
      fvarcevent[2]->SetMaximum(25);
      fvarcevent[2]->SetOption("COLZ");
      fvarcevent[2]->Draw();
      
      Int_t pedchn=1;
      if (pedchn==1) {
          for (Int_t i=0;i<36;i++) {fvt[i]->Draw();}
      }
      
      for (Int_t i=0;i<23;i++) {
          f1[i]->Draw();
      }
      
      for (Int_t i=0;i<34;i++) {
          fvline[i]->Draw();
      }
      
      for (Int_t i=0;i<16;i++) {
          fcratenums[i]->Draw();
      }  
      
      fplotFile_c->Update();
      
      if(!gQuickPlots) {
          fplotFile_c->Print(bookName.c_str());
          if(gPlotEachPage) {
              plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
              plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
              
              fplotFile_c->Print(plotNameGif.c_str());
              fplotFile_c->Print(plotNameEps.c_str());
          }
          MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
          plotCounter++;
      }
      
      outp->cd();
      plotNameR = Form("SPplotAtPage%i",plotCounterRoot);    
      fplotFile_c->SetName(plotNameR.c_str());
      fplotFile_c->Write();
      
      fplotFile_c->Clear();
      plotCounterRoot++;
  }//if !gQuickPlots || gAllRootFile


  //Map of RMSs - truncated:
//   fplotFile_c->Clear();
//   gPad->SetLogy(0);
//   gPad->SetLogx(0);
//   gPad->SetLogz(0);
//   //fRmsMapT_h->SetMinimum(.5);
//   //fRmsMapT_h->SetMaximum(25);
//   fRmsMapT_h->SetStats(0);
//   fRmsMapT_h->Draw("colz");
//   for(Int_t icrate = 0; icrate < Caryatid::CRATEMAX; icrate++) 
//     for(Int_t ivarc = 0; ivarc < Caryatid::VARCMAX; ivarc++)
//       fLines[icrate][ivarc]->Draw("same");
//   fplotFile_c->Update();
//   fplotFile_c->Print(bookName.c_str());
//   if(gPlotEachPage) {
//     plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
//     plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);

//     fplotFile_c->Print(plotNameGif.c_str());
//     fplotFile_c->Print(plotNameEps.c_str());
//   }
//   MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
//   plotCounter++;
//   fplotFile_c->Clear();
      
  //OM style RMS truncated map
  fplotFile_c->cd();
  gPad->SetLogy(0);
  gPad->SetLogx(0);
  gPad->SetLogz(0);
  
  fvarcevent[3]->SetStats(0);
  fvarcevent[3]->SetOption("COLZ");
  fvarcevent[3]->Draw();
  
  if (pedchn==1) {
      for (Int_t i=0;i<36;i++) {fvt[i]->Draw();}
  }
  
  for (Int_t i=0;i<23;i++) {
      f1[i]->Draw();
  }
  
  for (Int_t i=0;i<34;i++) {
      fvline[i]->Draw();
  }
  
  for (Int_t i=0;i<16;i++) {
      fcratenums[i]->Draw();
  }  
  
  fplotFile_c->Update();
  fplotFile_c->Print(bookName.c_str());
  if(gPlotEachPage) {
      plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
      plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
      
      fplotFile_c->Print(plotNameGif.c_str());
      fplotFile_c->Print(plotNameEps.c_str());
  }
  MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
  plotCounter++;
  
  outp->cd();
  plotNameR = Form("SPplotAtPage%i",plotCounterRoot);    
  fplotFile_c->SetName(plotNameR.c_str());
  fplotFile_c->Write();
  
  fplotFile_c->Clear();
  plotCounterRoot++;

  //Map of truncation effect on RMSs (RMS_RAW - RMS_TRUNC)
//   fplotFile_c->Clear();
//   gPad->SetLogy(0);
//   gPad->SetLogx(0);
//   gPad->SetLogz(0);
//   fDeltaRmsMapT_h->SetStats(0);
//   fDeltaRmsMapT_h->Draw("colz");
//   for(Int_t icrate = 0; icrate < Caryatid::CRATEMAX; icrate++) 
//     for(Int_t ivarc = 0; ivarc < Caryatid::VARCMAX; ivarc++)
//       fLines[icrate][ivarc]->Draw("same");
//   fplotFile_c->Update();
//   fplotFile_c->Print(bookName.c_str());
//   if(gPlotEachPage) {
//     plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
//     plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
    
//     fplotFile_c->Print(plotNameGif.c_str());
//     fplotFile_c->Print(plotNameEps.c_str());
//   }
//   MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
//   plotCounter++;
//   fplotFile_c->Clear();

  //OM style Effect of truncation on RMS map
  fplotFile_c->cd();
  gPad->SetLogy(0);
  gPad->SetLogx(0);
  gPad->SetLogz(0);
  
  fvarcevent[4]->SetStats(0);
  fvarcevent[4]->SetOption("COLZ");
  fvarcevent[4]->Draw();
  
  pedchn=1;
  if (pedchn==1) {
      for (Int_t i=0;i<36;i++) {fvt[i]->Draw();}
  }
  
  for (Int_t i=0;i<23;i++) {
      f1[i]->Draw();
  }
  
  for (Int_t i=0;i<34;i++) {
      fvline[i]->Draw();
  }
  
  for (Int_t i=0;i<16;i++) {
      fcratenums[i]->Draw();
  }  
  
  fplotFile_c->Update();
  fplotFile_c->Print(bookName.c_str());
  if(gPlotEachPage) {
      plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
      plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
      
      fplotFile_c->Print(plotNameGif.c_str());
      fplotFile_c->Print(plotNameEps.c_str());
  }
  MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
  plotCounter++;

  outp->cd();
  plotNameR = Form("SPplotAtPage%i",plotCounterRoot);    
  fplotFile_c->SetName(plotNameR.c_str());
  fplotFile_c->Write();
  
  fplotFile_c->Clear();
  plotCounterRoot++;

  if(gCompareSparTable){
      //OM style Spars. Thresh. Comparison
      fplotFile_c->cd();
      gPad->SetLogy(0);
      gPad->SetLogx(0);
      gPad->SetLogz(0);
      
      fvarcevent[9]->SetStats(0);
      fvarcevent[9]->SetOption("COLZ");
      fvarcevent[9]->Draw();
  
      pedchn=1;
      if (pedchn==1) {
          for (Int_t i=0;i<36;i++) {fvt[i]->Draw();}
      }
      
      for (Int_t i=0;i<23;i++) {
          f1[i]->Draw();
      }
      
      for (Int_t i=0;i<34;i++) {
          fvline[i]->Draw();
      }
      
      for (Int_t i=0;i<16;i++) {
          fcratenums[i]->Draw();
      }  
      
      fplotFile_c->Update();
      fplotFile_c->Print(bookName.c_str());
      if(gPlotEachPage) {
          plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
          plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
          
          fplotFile_c->Print(plotNameGif.c_str());
          fplotFile_c->Print(plotNameEps.c_str());
      }
      MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
      plotCounter++;
      
      outp->cd();
      plotNameR = Form("SPplotAtPage%i",plotCounterRoot);    
      fplotFile_c->SetName(plotNameR.c_str());
      fplotFile_c->Write();
      
      fplotFile_c->Clear();
      plotCounterRoot++;    
      
  }

  if(!gQuickPlots || gAllRootFile) {
      //Map of Entries:
//   fplotFile_c->Clear();
//       gPad->SetLogy(0);
//       gPad->SetLogx(0);
//       gPad->SetLogz(0);
//       fEntriesMap_h->SetStats(0);
//       fEntriesMap_h->Draw("colz");
//       for(Int_t icrate = 0; icrate < Caryatid::CRATEMAX; icrate++) 
//           for(Int_t ivarc = 0; ivarc < Caryatid::VARCMAX; ivarc++)
//               fLines[icrate][ivarc]->Draw("same");
//       fplotFile_c->Update();
//       fplotFile_c->Print(bookName.c_str());
//       if(gPlotEachPage) {
//           plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
//           plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
          
//           fplotFile_c->Print(plotNameGif.c_str());
//           fplotFile_c->Print(plotNameEps.c_str());
//       }
//       MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
//       plotCounter++;
   
      //OM style Trigger per Channel map         
      fplotFile_c->cd();
      gPad->SetLogy(0);
      gPad->SetLogx(0);
      gPad->SetLogz(0);
      
      fvarcevent[5]->SetStats(0);
      fvarcevent[5]->SetOption("COLZ");
      fvarcevent[5]->Draw();
      
      Int_t pedchn=1;
      if (pedchn==1) {
          for (Int_t i=0;i<36;i++) {fvt[i]->Draw();}
      }
      
      for (Int_t i=0;i<23;i++) {
          f1[i]->Draw();
      }
      
      for (Int_t i=0;i<34;i++) {
          fvline[i]->Draw();
      }
      
      for (Int_t i=0;i<16;i++) {
          fcratenums[i]->Draw();
      }  
      
      fplotFile_c->Update();
      
      if(!gQuickPlots) {
          fplotFile_c->Print(bookName.c_str());
          if(gPlotEachPage) {
              plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
              plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
          
              fplotFile_c->Print(plotNameGif.c_str());
              fplotFile_c->Print(plotNameEps.c_str());
          }
          MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
          plotCounter++;
      }
 
      outp->cd();
      plotNameR = Form("SPplotAtPage%i",plotCounterRoot);    
      fplotFile_c->SetName(plotNameR.c_str());
      fplotFile_c->Write();

      fplotFile_c->Clear();
      plotCounterRoot++;   
       
//Map of errors:
//       fplotFile_c->Clear();
//       gPad->SetLogy(0);
//       gPad->SetLogx(0);
//       gPad->SetLogz(0);
//       fErrorMap_h->SetStats(0);
//       fErrorMap_h->Draw("colz");
//       for(Int_t icrate = 0; icrate < Caryatid::CRATEMAX; icrate++) 
//           for(Int_t ivarc = 0; ivarc < Caryatid::VARCMAX; ivarc++)
//               fLines[icrate][ivarc]->Draw("same");
//       fplotFile_c->Update();
//       fplotFile_c->Print(bookName.c_str());
//       if(gPlotEachPage) {
//           plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
//           plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
          
//       fplotFile_c->Print(plotNameGif.c_str());
//       fplotFile_c->Print(plotNameEps.c_str());
//       }
//       MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
//       plotCounter++;
//       fplotFile_c->Clear();
      
      //OM style RMS truncated map
      fplotFile_c->cd();
      gPad->SetLogy(0);
      gPad->SetLogx(0);
      gPad->SetLogz(0);
      
      fvarcevent[6]->SetStats(0);
      fvarcevent[6]->SetOption("COLZ");
      fvarcevent[6]->Draw();
      
      pedchn=1;
      if (pedchn==1) {
          for (Int_t i=0;i<36;i++) {fvt[i]->Draw();}
      }
      
      for (Int_t i=0;i<23;i++) {
          f1[i]->Draw();
      }
      
      for (Int_t i=0;i<34;i++) {
          fvline[i]->Draw();
      }
      
      for (Int_t i=0;i<16;i++) {
          fcratenums[i]->Draw();
      }  
      
      fplotFile_c->Update();
     
      if(!gQuickPlots) {
          fplotFile_c->Print(bookName.c_str());
          if(gPlotEachPage) {
              plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
              plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
              
              fplotFile_c->Print(plotNameGif.c_str());
              fplotFile_c->Print(plotNameEps.c_str());
          }
          MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
          plotCounter++;
      }

      outp->cd();
      plotNameR = Form("SPplotAtPage%i",plotCounterRoot);    
      fplotFile_c->SetName(plotNameR.c_str());
      fplotFile_c->Write();

      fplotFile_c->Clear();
      plotCounterRoot++;

  }//if !gQuickPlots || gAllRootFile


  //Sparsification Threshold 1D:
  string histName;
  histName = "Recalculated Sparsification Threshold";
  histName += Form(" (%i Sigma)",Caryatid::GetSparsFactor());
  histName += Form(" -  Run %i",frun);
  
  fplotFile_c->cd();
  gPad->SetLogy(1);
  fSparcRaw_h->SetXTitle("ADC Counts");
  fSparcRaw_h->SetTitle(histName.c_str());
  fSparcRaw_h->SetStats(0);
  fSparcRaw_h->SetLineStyle(3);
  fSparcRaw_h->Draw();
  fSparc_h->SetLineColor(4);
  fSparc_h->Draw("same");
  fSparcLGPIN_h->SetLineColor(6);
  fSparcLGPIN_h->Draw("same");
  fSparcHGPIN_h->SetLineColor(15);
  fSparcHGPIN_h->Draw("same");
  leg->Clear();
  leg->AddEntry(fSparcRaw_h,"No Truncation","l");
  leg->AddEntry(fSparc_h,"PMT Channels","l");
  leg->AddEntry(fSparcHGPIN_h,"HIGH GAIN PINs","l");
  leg->AddEntry(fSparcLGPIN_h,"LOW GAIN PINs","l");
  //leg->SetHeader("The Legend Title");
  leg->Draw("same");
  fplotFile_c->Update();

  
  fplotFile_c->Print("LastSparsificationTable.gif");
  TImage *img = TImage::Open("LastSparsificationTable.gif");
  if (!img) {
      printf("Could not find Caryatid image... exit\n");
  }
  
  if(!gQuickPlots){ 
      fplotFile_c->Print(bookName.c_str());     
  } 
  else fplotFile_c->Print("LastSparsificationTable.eps");

  if(gPlotEachPage) {
    plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
    plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
    
    fplotFile_c->Print(plotNameGif.c_str());
    fplotFile_c->Print(plotNameEps.c_str());
  }
  MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
  plotCounter++;

  outp->cd();
  plotNameR = Form("SPplotAtPage%i",plotCounterRoot);    
  fplotFile_c->SetName(plotNameR.c_str());
  fplotFile_c->Write();

  fplotFile_c->Clear();
  plotCounterRoot++;
  
  img->SetName("LastSparsHisto");
  img->Write();
  img->Delete();


  if(!gQuickPlots || gAllRootFile) {
    //Map of sparsification thresholds:
//     fplotFile_c->Clear();
//     gPad->SetLogy(0);
//     gPad->SetLogx(0);
//     gPad->SetLogz(0);
//     fSparcMap_h->SetStats(0);
//     //fSparcMap_h->SetMaximum(50);
//     fSparcMap_h->Draw("colz");
//     for(Int_t icrate = 0; icrate < Caryatid::CRATEMAX; icrate++) 
//       for(Int_t ivarc = 0; ivarc < Caryatid::VARCMAX; ivarc++)
// 	fLines[icrate][ivarc]->Draw("same");
//     fplotFile_c->Update();
//     fplotFile_c->Print(bookName.c_str());
//     if(gPlotEachPage) {
//       plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
//       plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);

//       fplotFile_c->Print(plotNameGif.c_str());
//       fplotFile_c->Print(plotNameEps.c_str());
//     }
//     MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
//     plotCounter++;


    //OM style sparsification threshold map
    fplotFile_c->cd();
    gPad->SetLogy(0);
    gPad->SetLogx(0);
    gPad->SetLogz(0);
    
    fvarcevent[7]->SetStats(0);
    fvarcevent[7]->SetOption("COLZ");
    fvarcevent[7]->Draw();
      
    pedchn=1;
    if (pedchn==1) {
          for (Int_t i=0;i<36;i++) {fvt[i]->Draw();}
    }
    
    for (Int_t i=0;i<23;i++) {
        f1[i]->Draw();
    }
    
    for (Int_t i=0;i<34;i++) {
        fvline[i]->Draw();
    }
      
    for (Int_t i=0;i<16;i++) {
        fcratenums[i]->Draw();
    }  
    
    fplotFile_c->Update();
    
    
    if(!gQuickPlots) {
        fplotFile_c->Print(bookName.c_str());
        if(gPlotEachPage) {
            plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
            plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
            
            fplotFile_c->Print(plotNameGif.c_str());
            fplotFile_c->Print(plotNameEps.c_str());
        }
        MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
        plotCounter++;
    }
    
    outp->cd();
    plotNameR = Form("SPplotAtPage%i",plotCounterRoot);    
    fplotFile_c->SetName(plotNameR.c_str());
    fplotFile_c->Write();
    
    fplotFile_c->Clear();
    plotCounterRoot++;
      
  }

  //
  //OUTLIERS ANALYSIS PLOTS:
  //


  if(!gQuickPlots || gAllRootFile) {

    //Multiplicity of Truncation Outliers per channel
    fplotFile_c->cd();
    gPad->SetLogy(1);
    fPerTrunc_h->SetXTitle("# of Outliers Per Channel");
    fPerTrunc_h->SetMinimum(0.5);
    fPerTrunc_h->Draw();
    fplotFile_c->Update();
    
    if(!gQuickPlots) {
        fplotFile_c->Print(bookName.c_str());
        if(gPlotEachPage) {
            plotNameGif += Form("SPplotAtPage%i.gif",plotCounter); 
            plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
            
            fplotFile_c->Print(plotNameGif.c_str());
            fplotFile_c->Print(plotNameEps.c_str());
        }
        MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
        plotCounter++;
    }
        
    outp->cd();
    plotNameR = Form("SPplotAtPage%i",plotCounterRoot);    
    fplotFile_c->SetName(plotNameR.c_str());
    fplotFile_c->Write();
    
    fplotFile_c->Clear();
    plotCounterRoot++;
  
    //Crate Occupancy of Outliers:
    fplotFile_c->cd();
    gPad->SetLogy(0);
    fTruncOccCM_h->SetXTitle("Crate#");
    fTruncOccCM_h->Draw();
    fplotFile_c->Update();
    
    if(!gQuickPlots) {
        fplotFile_c->Print(bookName.c_str());
        if(gPlotEachPage) {
            
            plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
            plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
            
            fplotFile_c->Print(plotNameGif.c_str());
            fplotFile_c->Print(plotNameEps.c_str());  
        }
        
        MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
        plotCounter++;
    }
    
    outp->cd();
    plotNameR = Form("SPplotAtPage%i",plotCounterRoot);    
    fplotFile_c->SetName(plotNameR.c_str());
    fplotFile_c->Write();

    fplotFile_c->Clear();
    plotCounterRoot++;
  

    //VA channels Occupancy of Outliers:
    fplotFile_c->cd();
    gPad->SetLogy(0);
    fTruncOccVA_h->SetXTitle("VA Chip Channels");
    fTruncOccVA_h->Draw();
    fplotFile_c->Update();

    if(!gQuickPlots) {
        fplotFile_c->Print(bookName.c_str());
        if(gPlotEachPage) {
            plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
            plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
            
            fplotFile_c->Print(plotNameGif.c_str());
            fplotFile_c->Print(plotNameEps.c_str());    
        }
        MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
        plotCounter++;
    }
    
    outp->cd();
    plotNameR = Form("SPplotAtPage%i",plotCounterRoot);    
    fplotFile_c->SetName(plotNameR.c_str());
    fplotFile_c->Write();
    
    fplotFile_c->Clear();
    plotCounterRoot++;


    //Plane occupancy  of outliers:
    fplotFile_c->cd();
    gPad->SetLogy(0);
    fOutDetMap_h->SetXTitle("Plane#");
    fOutDetMap_h->SetTitle("Plane Occupancy of Outliers");
    fOutDetMap_h->Draw();
    fplotFile_c->Update();
    
    if(!gQuickPlots) {
        fplotFile_c->Print(bookName.c_str());
        if(gPlotEachPage) {
            plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
            plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
            
            fplotFile_c->Print(plotNameGif.c_str());
            fplotFile_c->Print(plotNameEps.c_str());
        }
        MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
        plotCounter++;
    }

    outp->cd();
    plotNameR = Form("SPplotAtPage%i",plotCounterRoot);    
    fplotFile_c->SetName(plotNameR.c_str());
    fplotFile_c->Write();

    fplotFile_c->Clear();
    plotCounterRoot++;


//Map of outliers in FEE space:
//     fplotFile_c->cd();
//     gPad->SetLogy(0);
//     gPad->SetLogx(0);
//     gPad->SetLogz(0);
//     fOutMap_h->SetMaximum(15);
//     fOutMap_h->SetStats(0);
//     fOutMap_h->Draw("colz");
//     for(Int_t icrate = 0; icrate < Caryatid::CRATEMAX; icrate++)
//       for(Int_t ivarc = 0; ivarc < Caryatid::VARCMAX; ivarc++)
// 	fLines[icrate][ivarc]->Draw("same");
//     fplotFile_c->Update();
//     fplotFile_c->Print(bookName.c_str());
//     if(gPlotEachPage) {
//       plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
//       plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);

//       fplotFile_c->Print(plotNameGif.c_str());
//       fplotFile_c->Print(plotNameEps.c_str());
//     }
//     MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
//     plotCounter++;
//     fplotFile_c->Clear();
    
    //OM style outliers occupancy map
    fplotFile_c->cd();   
    gPad->SetLogy(0);
    gPad->SetLogx(0);
    gPad->SetLogz(0);
    
    fvarcevent[8]->SetStats(0);
    fvarcevent[8]->SetOption("COLZ");
    fvarcevent[8]->Draw();
      
    pedchn=1;
    if (pedchn==1) {
          for (Int_t i=0;i<36;i++) {fvt[i]->Draw();}
    }
    
    for (Int_t i=0;i<23;i++) {
        f1[i]->Draw();
    }
    
    for (Int_t i=0;i<34;i++) {
        fvline[i]->Draw();
    }
    
    for (Int_t i=0;i<16;i++) {
        fcratenums[i]->Draw();
    }  
    
    fplotFile_c->Update();
    
    if(!gQuickPlots) {
        fplotFile_c->Print(bookName.c_str());
        if(gPlotEachPage) {
            plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
            plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
            
            fplotFile_c->Print(plotNameGif.c_str());
            fplotFile_c->Print(plotNameEps.c_str());
        }
        MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
        plotCounter++;
    }
    
    outp->cd();
    plotNameR = Form("SPplotAtPage%i",plotCounterRoot);    
    fplotFile_c->SetName(plotNameR.c_str());
    fplotFile_c->Write();
    
    fplotFile_c->Clear();
    plotCounterRoot++;
  
  }//if !gQuickPlots || gAllRootFile	    

  
  //
  // COMPARISON BETWEEN SP TABLES AND DAQ TABLES:
  //


  if(!gQuickPlots || gAllRootFile) {
    if(gCompareSparTable) {
        
      //Histogram of Pedestal difference between SP values and online values
      fplotFile_c->cd();
      gPad->SetLogx(0);
      gPad->SetLogy(0);
      fDeltaMean_h->SetStats(1);
      fDeltaMean_h->Draw();
      fplotFile_c->Update();

      if(!gQuickPlots) {
          fplotFile_c->Print(bookName.c_str());
          if(gPlotEachPage) {
              plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
              plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
              
              fplotFile_c->Print(plotNameGif.c_str());
              fplotFile_c->Print(plotNameEps.c_str());
          }
          MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
          plotCounter++;
      }

      outp->cd();
      plotNameR = Form("SPplotAtPage%i",plotCounterRoot);    
      fplotFile_c->SetName(plotNameR.c_str());
      fplotFile_c->Write();

      fplotFile_c->Clear();
      plotCounterRoot++;

      //Map of pedestal variation:
      fplotFile_c->cd();
      gPad->SetLogz(0);
      gPad->SetLogx(0);
      gPad->SetLogy(0);
      fDeltaCompMean_h->SetStats(0);
      fDeltaCompMean_h->Draw("colz");
      for(Int_t icrate = 0; icrate < Caryatid::CRATEMAX; icrate++)
	for(Int_t ivarc = 0; ivarc < Caryatid::VARCMAX; ivarc++)
	  fLines[icrate][ivarc]->Draw("same");
      fplotFile_c->Update();
      
      if(!gQuickPlots) {
          fplotFile_c->Print(bookName.c_str());
          if(gPlotEachPage) {
              plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
              plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
              
              fplotFile_c->Print(plotNameGif.c_str());
              fplotFile_c->Print(plotNameEps.c_str());
          }
          MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
          plotCounter++;
      }

      outp->cd();
      plotNameR = Form("SPplotAtPage%i",plotCounterRoot);    
      fplotFile_c->SetName(plotNameR.c_str());
      fplotFile_c->Write();

      fplotFile_c->Clear();
      plotCounterRoot++;

      //Sparsification Variation Histogram:
      fplotFile_c->cd();
      gPad->SetLogy(1);
      fDeltaSparc_h->SetStats(1);
      fDeltaSparc_h->Draw();
      fplotFile_c->Update();
      
      if(!gQuickPlots) {
          fplotFile_c->Print(bookName.c_str());
          if(gPlotEachPage) {
              plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
              plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
              
              fplotFile_c->Print(plotNameGif.c_str());
              fplotFile_c->Print(plotNameEps.c_str());  
          }
          MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
          plotCounter++;
      }

      outp->cd();
      plotNameR = Form("SPplotAtPage%i",plotCounterRoot);    
      fplotFile_c->SetName(plotNameR.c_str());
      fplotFile_c->Write();

      fplotFile_c->Clear();
      plotCounterRoot++;

      //Map of Sparsification Variation (spar_SP - spar_DAQ)
      fplotFile_c->cd();
      gPad->SetLogz(0);
      gPad->SetLogx(0);
      gPad->SetLogy(0);
      fDeltaSparcMap_h->SetStats(0);
      //fDeltaSparcMap_h->SetMaximum(20);
      //fDeltaSparcMap_h->SetMinimum(-10);
      fDeltaSparcMap_h->Draw("colz");
      for(Int_t icrate = 0; icrate < Caryatid::CRATEMAX; icrate++)
	for(Int_t ivarc = 0; ivarc < Caryatid::VARCMAX; ivarc++)
	  fLines[icrate][ivarc]->Draw("same");
      fplotFile_c->Update();

      if(!gQuickPlots) {
          fplotFile_c->Print(bookName.c_str());
          if(gPlotEachPage) {
              plotNameGif += Form("SPplotAtPage%i.gif",plotCounter);
              plotNameEps += Form("SPplotAtPage%i.eps",plotCounter);
              
              fplotFile_c->Print(plotNameGif.c_str());
              fplotFile_c->Print(plotNameEps.c_str());
          }
          MSG("CaryatidAna",Msg::kInfo) << "Included Page " << plotCounter << endl;
          plotCounter++;
      }

      outp->cd();
      plotNameR = Form("SPplotAtPage%i",plotCounterRoot);    
      fplotFile_c->SetName(plotNameR.c_str());
      fplotFile_c->Write();

      fplotFile_c->Clear();
      plotCounterRoot++;

    }
  }//if !gQuickPlots || gAllRootFile
  
  //Last page:
  fplotFile_c->Clear();
  fplotFile_c->Update();
  fplotFile_c->Print(bookNameEnd.c_str());
  fplotFile_c->Clear();
  
  MSG("CaryatidAna",Msg::kInfo) << "All Plots are done!" << endl;
      
  delete fplotFile_c;
  outp->Close();
}

//-------------------------------------------------

//**** Useful Functions for some dealing with histograms ****

// Use: h->SetAxisRange( FindSecondBin( h ), FindLastBin( h) , "Y" );

//Second bin whose content is != 0

Float_t  CaryatidAna::FindFirstBin( const TH1* histogram ) {

  Int_t  lowestBin = 0;
  Int_t  allBin = histogram->GetNbinsX();

  for (Int_t  iBin = 1; iBin <= allBin; iBin++) {
    if ( histogram->GetBinContent( iBin ) > 0 ) {
      lowestBin = iBin;
      break;
    }
  }
  return histogram->GetBinCenter( lowestBin );
}

//-------------------------------------------------

//Last bin whose content is != 0

Float_t  CaryatidAna::FindLastBin( const TH1* histogram ) {
  
  Int_t  allBin = histogram->GetNbinsX();
  Int_t  highestBin = allBin;

  for (Int_t  iBin = allBin; iBin >= 1; iBin--) {
    if( histogram->GetBinContent( iBin ) > 0 ) {
      highestBin = iBin;
      break;
    }
  }
  return histogram->GetBinCenter( highestBin );
}

//-------------------------------------------------

void CaryatidAna::InitAnaVariables() {

  //Initialising members:
  fMeanT1_h = new TH1F("fMeanT1_h","Distribution of the Pedestals's Means",600,0,1200);
  fRmsT1_h  = new TH1F("fRmsT1_h", "Distribution of the Pedestals's RMSs (ALL channels)", 31,-0.5,30.5);

  fMeanT2_h = new TH1F("fMeanT2_h","Distribution of the Pedestals's Means",600,0,1200);
  fRmsT2_h  = new TH1F("fRmsT2_h", "Distribution of the Pedestals's RMSs (ALL channels)", 31,-0.5,30.5);

  fMeanRaw_h = new TH1F("fMeanRaw_h","Distribution of the Pedestals's Means",600,0,1200);
  fRmsRaw_h     = new TH1F("fRmsRaw_h", "Distribution of the Pedestals's RMSs (ALL channels)", 51,-0.5,50.5);

  fRmsPMT_h  = new TH1F("fRmsPMT_h", "Distribution of the Pedestals's RMSs (PMT channels)", 31,-0.5,30.5);
  fRmsCM_h   = new TH1F("fRmsCM_h", "Distribution of the Pedestals's RMSs (CM channels)",   31,-0.5,30.5);
  fRmsPINLG_h  = new TH1F("fRmsPINLG_h", "Distribution of the Pedestals's RMSs (LG PIN)",   31,-0.5,30.5);
  fRmsPINHG_h  = new TH1F("fRmsPINHG_h", "Distribution of the Pedestals's RMSs (HG PIN)",   31,-0.5,30.5);

  fRmsRawPMT_h  = new TH1F("fRmsRawPMT_h", "Distribution of the Pedestals's RMSs (PMT channels)", 51,-0.5,50.5);
  fRmsRawCM_h   = new TH1F("fRmsRawCM_h", "Distribution of the Pedestals's RMSs (CM channels)",   31,-0.5,30.5);
  fRmsRawPINLG_h  = new TH1F("fRmsRawPINLG_h", "Distribution of the Pedestals's RMSs (LG PIN)",   31,-0.5,30.5);
  fRmsRawPINHG_h  = new TH1F("fRmsRawPINHG_h", "Distribution of the Pedestals's RMSs (HG PIN)",   31,-0.5,30.5);

  //Truncation Outliers distributions:
  fTruncOcc_h   = new TH1F("fTruncOcc_h",   "Pedestal Occupancy",15,0,15);
  fTruncOccCM_h = new TH1F("fTruncOccCM1_h","Truncated Outliers Occupancy wrt Crate#",16,0,16);
  fTruncOccVA_h = new TH1F("fTruncOccVA1_h","Truncated Outliers Occupancy wrt VA-channel#",22,0,22);
  fPerTrunc_h   = new TH1F("fPerTrunc_h",   "Truncated Outliers Multiplicity Per Channel", 15,0,15);
  fOutDetMap_h  = new TH1F("fOutDetMap_h",  "Truncated Outliers Occupancy wrt Plane#", 125,0,500);

  //Maps:
  fMeanMap_h = new TH2F("fMeanMap_h","Mapping of the MEAN per Channels without Truncation",576,0,576,90,0,90);
  fMeanMap_h->SetXTitle("3x6x2xCrate# + 6x2xVARC# + 2xVMM# + VFB#");
  fMeanMap_h->SetYTitle("22xVA-chip# + VA-chip-Channel#");

  fRmsMap_h  = new TH2F("fRmsMap_h", "Mapping of the RMS (no Truncation) {if RMS < 25}",576,0,576,90,0,90);
  fRmsMap_h->SetXTitle("3x6x2xCrate# + 6x2xVARC# + 2xVMM# + VFB#");
  fRmsMap_h->SetYTitle("22xVA-chip# + VA-chip-Channel#");

  fRmsMapT_h  = new TH2F("fRmsMapT_h", "Mapping of the RMS (truncated)",576,0,576,90,0,90);
  fRmsMapT_h->SetXTitle("3x6x2xCrate# + 6x2xVARC# + 2xVMM# + VFB#");
  fRmsMapT_h->SetYTitle("22xVA-chip# + VA-chip-Channel#");

  fOutMap_h = new TH2F("fOutMap_h","Map of Outliers Occupancy",576,0,576,90,0,90);
  fOutMap_h->SetXTitle("3x6x2xCrate# + 6x2xVARC# + 2xVMM# + VFB#");
  fOutMap_h->SetYTitle("22xVA-chip# + VA-chip-Channel#");

  fEntriesMap_h = new TH2F("fEntriesMap_h",
			   "Mapping of the number of triggers per Channels (no truncation)",
			   576,0,576,90,0,90);
  fEntriesMap_h->SetXTitle("3x6x2xCrate# + 6x2xVARC# + 2xVMM# + VFB#");
  fEntriesMap_h->SetYTitle("22xVA-chip# + VA-chip-Channel#");

  fSparcMap_h = new TH2F("fSparcMap_h",
			 "Mapping of the Sparsification Threshold per Channels with Truncation",
			 576,0,576,90,0,90);
  fSparcMap_h->SetXTitle("3x6x2xCrate# + 6x2xVARC# + 2xVMM# + VFB#");
  fSparcMap_h->SetYTitle("22xVA-chip# + VA-chip-Channel#");

  fDeltaSparcMap_h= new TH2F("fDeltaSparcMap_h",
			     "Mapping of the Sparsification Threshold Variation ('MyValues'-'TableValues')",
			     576,0,576,90,0,90);
  fDeltaSparcMap_h->SetXTitle("3x6x2xCrate# + 6x2xVARC# + 2xVMM# + VFB#");
  fDeltaSparcMap_h->SetYTitle("22xVA-chip# + VA-chip-Channel#");

  fDeltaMeanMapT_h = new TH2F("fDeltaMeanMapT_h",
			      "Effect of truncation on the MEAN {Mean(non-truncated) - MEAN(truncated)}",
			      576,0,576,90,0,90);
  fDeltaMeanMapT_h->SetXTitle("3x6x2xCrate# + 6x2xVARC# + 2xVMM# + VFB#");
  fDeltaMeanMapT_h->SetYTitle("22xVA-chip# + VA-chip-Channel#");
  
  //Sparsification threshoold histogram:
  fSparc_h      = new TH1F("fSparc_h","",95,0,95);
  fSparcRaw_h   = new TH1F("fSparcRaw_h","",95,0,95);
  fSparcLGPIN_h = new TH1F("fSparcLGPIN_h","",95,0,95);
  fSparcHGPIN_h = new TH1F("fSparcHGPIN_h","",95,0,95);

  //Creating the TLines:
  for(Int_t icrate = 0; icrate < Caryatid::CRATEMAX; icrate++) {
    for(Int_t ivarc = 0; ivarc < Caryatid::VARCMAX; ivarc++) { 
 
      fLines[icrate][ivarc] = new TLine(3*6*2*icrate+6*2*ivarc,0,
					3*6*2*icrate+6*2*ivarc,90);
      
      fLines[icrate][ivarc]->SetLineColor(6);
      fLines[icrate][ivarc]->SetLineWidth(2);
      fLines[icrate][ivarc]->SetLineStyle(3);
    }
  }

  //Comparison Tables histograms:


  //Pedestal:

  fDeltaMean_h = new TH1F("fDeltaMean_h", 
			  "Difference between Caryatid Table and online Tables MEANs",10,-5,5);
  fDeltaMean_h->SetXTitle("#Delta MEAN('CaryatidValues'-'OnlineTablesValues')");
  
  fDeltaCompMean_h = new TH2F("fDeltaCompMean_h",
			      "Difference between Caryatid Table and online Table MEANs",
			      576,0,576,90,0,90);
  fDeltaCompMean_h->SetXTitle("3x6x2xCrate# + 6x2xVARC# + 2xVMM# + VFB#");
  fDeltaCompMean_h->SetYTitle("22xVA-chip# + VA-chip-Channel#");


  //Sparsification:

  fDeltaSparc_h = new TH1F("fDeltaSparc_h", 
			  "Difference between Caryatid Table and online Tables RMSs",50,-25,25);
			  //2*gToleranceSparTable+1,
			  //-gToleranceSparTable-0.5,
			  //gToleranceSparTable+0.5);
  fDeltaSparc_h->SetXTitle("#Delta RMS('CaryatidValues'-'OnlineTablesValues')");

  fDeltaRmsMapT_h = new TH2F("fDeltaRmsMapT_h",
			     "Effect of Truncation on pedestals width {RMS(non-truncated) - RMS(truncated)}",
			     576,0,576,90,0,90);
  fDeltaRmsMapT_h->SetXTitle("3x6x2xCrate# + 6x2xVARC# + 2xVMM# + VFB#");
  fDeltaRmsMapT_h->SetYTitle("22xVA-chip# + VA-chip-Channel#");

  fErrorMap_h = new TH2F("fErrorMap_h",
			 "Error Code Map",
			 576,0,576,90,0,90);
  fErrorMap_h->SetXTitle("3x6x2xCrate# + 6x2xVARC# + 2xVMM# + VFB#");
  fErrorMap_h->SetYTitle("22xVA-chip# + VA-chip-Channel#");

  
  //Logical channel maps vmm vs varc per crate (like OM)
  
  fpederrorpad=new TCanvas("Rogue pedestal channels",
			   "Rogue pedestal channels",
			   10,10,400,400);

  fvarccan=new TCanvas*[9];
  fvarcpad=new TPad*[8];
  fvarcevent=new TH2F*[9];
  
  


  for (Int_t ni=0; ni<10; ni++) {
      
      Int_t pedchn=0;
      string canname;
      string evname;
      string padname;
      
      string temp="Spar. Thresh. Comparison Map (|Caryatid-Current| > ";
      ostringstream oss;
      oss << temp << gToleranceSparTable;
      string temp2(oss.str());
      temp2+=" ADC)";

      switch (ni) {
      case 0:
          canname="Pedestal ADC MEAN Channel Map (No Truncation)";
          canname += Form(" -  Run %i",frun);
          evname="Pedestal ADC MEAN Channel Map (No Truncation)";
          evname += Form(" -  Run %i",frun);
          padname="Pedestal ADC MEAN per Channel Map (No Truncation)";
          pedchn=1;
          break;
      case 1:
          canname="Effect of Truncation on MEAN";
          canname += Form(" -  Run %i",frun);
          evname="Effect of Truncation on MEAN (Untruncated - Truncated Mean)";
          evname += Form(" -  Run %i",frun);
          padname="Effect of truncation on MEAN";
          pedchn=1;
          break;
      case 2:
          canname="Pedestal ADC RMS Channel Map (No Truncation) {RMS < 25}";
          canname += Form(" -  Run %i",frun);
          evname="Pedestal ADC RMS Channel Map (No Truncation) {RMS < 25}";
          evname += Form(" -  Run %i",frun);
          padname="Pedestal ADC RMS Channel Map (No Truncation) {RMS < 25}";
          pedchn=1;
          break;
      case 3:
          canname="Pedestal ADC RMS Channel Map (Truncated)";
          canname += Form(" -  Run %i",frun);
          evname="Pedestal ADC RMS Channel Map (Truncated)";
          evname += Form(" -  Run %i",frun);
          padname="Pedestal ADC RMS Channel Map (Truncated)";
          pedchn=1;
          break;
      case 4:
          canname="Effect of Truncation on RMS";
          canname += Form(" -  Run %i",frun);
          evname="Effect of Truncation on RMS (Untruncated - Truncated RMS)";
          evname += Form(" -  Run %i",frun);
          padname="Effect of Truncation on RMS";
          pedchn=1;
          break;
      case 5:
          canname="Pedestal Number of Triggers per Channel Map (No Truncation)";
          canname += Form(" -  Run %i",frun);
          evname="Pedestal Number of Triggers per Channel Map (No Truncation)";
          evname += Form(" -  Run %i",frun);
          padname="Pedestal Number of Triggers per Channel Map (No Truncation)";
          pedchn=1;
          break;
      case 6:
          canname="Pedestal Issued XQT Signal Map";
          canname += Form(" -  Run %i",frun);
          evname="Pedestal Issued XQT signal Map";
          evname += Form(" -  Run %i",frun);
          padname="Pedestal Issued XQT Signal Map";
          pedchn=1;
         break;
      case 7:
          canname="Sparsification Threshold Map (No Truncation)";
          canname += Form(" -  Run %i",frun);
          evname="Sparsification Threshold Map (No Truncation)";
          evname += Form(" -  Run %i",frun);
          padname="Sparsification Threshold Map (No Truncation)";
          pedchn=1;
         break;
      case 8:
          canname="Outliers Occupancy Map";
          canname += Form(" -  Run %i",frun);
          evname="Outliers Occupancy Map";
          evname += Form(" -  Run %i",frun);
          padname="Outliers Occupancy Map";
          pedchn=1;
          break;
      case 9:
          canname=temp2;
          canname += Form(" -  Run %i",frun);
          evname=temp2;
          //evname="Spar. Thresh. Comparison Map";
          evname += Form(" -  Run %i",frun);
          padname=temp2;
          //padname="Spar. Thresh. Comparison Map";
          pedchn=1;
          break;
      default:
          break;
      }
      
      fvarccan[ni]=new TCanvas (canname.c_str(),canname.c_str(),
			  200,200,600,600);
      
      fvarcpad[ni]=new TPad(padname.c_str(),padname.c_str(),0,0,1,0.9);

      fvarcpad[ni]->SetGridx();
      fvarcpad[ni]->SetGridy();     

      if (pedchn==0) {
          fvarcevent[ni]=new TH2F(evname.c_str(),evname.c_str(),
                                  36,0,36,48,0,48);
          fvarcevent[ni]->GetXaxis()->SetNdivisions(36,kTRUE);
          fvarcevent[ni]->GetYaxis()->SetNdivisions(48,kTRUE);
      }
      else {
          fvarcevent[ni]=new TH2F(evname.c_str(),evname.c_str(),
                                  9*6*4,0,36,12*6*4,0,48);
          fvarcevent[ni]->GetXaxis()->SetNdivisions(36,kTRUE);
          fvarcevent[ni]->GetYaxis()->SetNdivisions(48,kTRUE);
      }
      fvarcevent[ni]->SetStats(kFALSE);
      
      
      fvarcevent[ni]->GetXaxis()->SetTickLength(0.001);
      fvarcevent[ni]->GetYaxis()->SetTickLength(0.001);
      
      if (ni==0) {fvarcevent[ni]->SetMaximum(1100);}
      if (ni==1) {fvarcevent[ni]->SetMaximum(5);}
      if (ni==1) {fvarcevent[ni]->SetMinimum(1);}
      if (ni==2) {fvarcevent[ni]->SetMaximum(25);}
      if (ni==3) {fvarcevent[ni]->SetMaximum(9);}
      if (ni==4) {fvarcevent[ni]->SetMaximum(55);}
      if (ni==4) {fvarcevent[ni]->SetMinimum(5);}
      if (ni==5) {fvarcevent[ni]->SetMaximum(820);}
      if (ni==6) {fvarcevent[ni]->SetMaximum(2);}
      if (ni==7) {fvarcevent[ni]->SetMaximum(45);}
      if (ni==8) {fvarcevent[ni]->SetMaximum(15);}
      if (ni==8) {fvarcevent[ni]->SetMinimum(1.5);}
      //if (ni==9) {fvarcevent[ni]->SetMaximum();}
      if (ni==9) {fvarcevent[ni]->SetMinimum(0.0);}
      
      if (pedchn==0) {
          for (Int_t i=1;i<49;i++) {
              if (i<37) {
                  if ((i+1)%3==0) {
                      char varc[2];
                      sprintf(varc,"%i",(i%9)/3);
                      fvarcevent[ni]->GetXaxis()->SetBinLabel(i,varc);
                  }
                  else{fvarcevent[ni]->GetXaxis()->SetBinLabel(i," ");}
              }
              if ((i+1)%2==0) {
                  char vmm[2];
                  sprintf(vmm,"%i",(i%12)/2);
                  fvarcevent[ni]->GetYaxis()->SetBinLabel(i,vmm);
              }
              else {fvarcevent[ni]->GetYaxis()->SetBinLabel(i," ");}
          }
      }else{
          for (Int_t ii=1;ii<288;ii++) {
              if (ii<216) {
                  fvarcevent[ni]->GetXaxis()->SetBinLabel(ii," ");
              }
              else {fvarcevent[ni]->GetYaxis()->SetBinLabel(ii," ");}
          }
      }
      
      fvarcevent[ni]->SetXTitle("VARC");
      fvarcevent[ni]->SetYTitle("VMM");
  }
  
  //VARC lines
  fvline=new TLine*[34];
  Int_t lcount=0;
  for (Int_t i=0;i<3;i++) {
      fvline[lcount]=new TLine((i+1)*9,0,(i+1)*9,48);
      fvline[lcount]->SetLineWidth(3);
      lcount++;
  }
  
  for (Int_t i=0;i<3;i++) {
      fvline[lcount]=new TLine(0,(i+1)*12,36,(i+1)*12);
      fvline[lcount]->SetLineWidth(3);
      lcount++;
  }
  
  for (Int_t i=0;i<8;i++) {
      fvline[lcount]=new TLine((i+1)*3+(i/2)*3,0,(i+1)*3+(i/2)*3,48);
      lcount++;
  }
  
  for (Int_t i=0;i<20;i++) {
      fvline[lcount]=new TLine(0,(i+1)*2+(i/5)*2,36,(i+1)*2+(i/5)*2);
      lcount++;
  }
  
  //crate numbers
  fcratenums=new TText*[16];
  for (Int_t i=0;i<16;i++) {
      char cr[2];
      sprintf(cr,"%i",i);
      fcratenums[i]=new TText(i%4*9+7.5+(1-i/10)*0.4,(3-(i/4))*12+10.2,cr);
      fcratenums[i]->SetTextSize(0.03);
  }
  
  //VARC labels
  fvt=new TText*[36];
  char fvtc[2];
  for (Int_t i=0;i<12;i++) {
      sprintf(fvtc,"%i",i%3);
      fvt[i]=new TText(i*3+1.3,-1.8,fvtc);
      fvt[i]->SetTextSize(0.03);
  }
  for (Int_t i=0;i<24;i++) {
      sprintf(fvtc,"%i",i%6);
      fvt[i+12]=new TText(-1.,i*2+0.7,fvtc);
      fvt[i+12]->SetTextSize(0.03);
  }
  
  
  //Exclusion Lines for vmm vs varcmaps 
  f1=new TPolyLine*[23];
  
  f1[0]=new TPolyLine(11);
  f1[0]->SetNextPoint(0,0);
  f1[0]->SetNextPoint(9,0);
  f1[0]->SetNextPoint(9,10);
  f1[0]->SetNextPoint(7,10);
  f1[0]->SetNextPoint(7,11);
  f1[0]->SetNextPoint(9,11);
  f1[0]->SetNextPoint(9,12);
  f1[0]->SetNextPoint(3,12);
  f1[0]->SetNextPoint(3,10);
  f1[0]->SetNextPoint(0,10);
  f1[0]->SetNextPoint(0,0);
  
  f1[1]=new TPolyLine(11);
  f1[1]->SetNextPoint(0+12-3,0);
  f1[1]->SetNextPoint(9+12-3,0);
  f1[1]->SetNextPoint(9+12-3,10);
  f1[1]->SetNextPoint(7+12-3,10);
  f1[1]->SetNextPoint(7+12-3,11);
  f1[1]->SetNextPoint(9+12-3,11);
  f1[1]->SetNextPoint(9+12-3,12);
  f1[1]->SetNextPoint(3+12-3,12);
  f1[1]->SetNextPoint(3+12-3,10);
  f1[1]->SetNextPoint(0+12-3,10);
  f1[1]->SetNextPoint(0+12-3,0);
  
  f1[2]=new TPolyLine(11);
  f1[2]->SetNextPoint(0,0+24);
  f1[2]->SetNextPoint(9,0+24);
  f1[2]->SetNextPoint(9,10+24);
  f1[2]->SetNextPoint(7,10+24);
  f1[2]->SetNextPoint(7,11+24);
  f1[2]->SetNextPoint(9,11+24);
  f1[2]->SetNextPoint(9,12+24);
  f1[2]->SetNextPoint(3,12+24);
  f1[2]->SetNextPoint(3,10+24);
  f1[2]->SetNextPoint(0,10+24);
  f1[2]->SetNextPoint(0,0+24);
  
  f1[3]=new TPolyLine(11);
  f1[3]->SetNextPoint(0,0+36);
  f1[3]->SetNextPoint(9,0+36);
  f1[3]->SetNextPoint(9,10+36);
  f1[3]->SetNextPoint(7,10+36);
  f1[3]->SetNextPoint(7,11+36);
  f1[3]->SetNextPoint(9,11+36);
  f1[3]->SetNextPoint(9,12+36);
  f1[3]->SetNextPoint(3,12+36);
  f1[3]->SetNextPoint(3,10+36);
  f1[3]->SetNextPoint(0,10+36);
  f1[3]->SetNextPoint(0,0+36);
  
  f1[4]=new TPolyLine(11);
  f1[4]->SetNextPoint(0+12-3,0+12);
  f1[4]->SetNextPoint(9+12-3,0+12);
  f1[4]->SetNextPoint(9+12-3,10+12);
  f1[4]->SetNextPoint(7+12-3,10+12);
  f1[4]->SetNextPoint(7+12-3,11+12);
  f1[4]->SetNextPoint(9+12-3,11+12);
  f1[4]->SetNextPoint(9+12-3,12+12);
  f1[4]->SetNextPoint(3+12-3,12+12);
  f1[4]->SetNextPoint(3+12-3,10+12);
  f1[4]->SetNextPoint(0+12-3,10+12);
  f1[4]->SetNextPoint(0+12-3,0+12);
  
  f1[5]=new TPolyLine(11);
  f1[5]->SetNextPoint(0+24-6,0+36);
  f1[5]->SetNextPoint(9+24-6,0+36);
  f1[5]->SetNextPoint(9+24-6,10+36);
  f1[5]->SetNextPoint(7+24-6,10+36);
  f1[5]->SetNextPoint(7+24-6,11+36);
  f1[5]->SetNextPoint(9+24-6,11+36);
  f1[5]->SetNextPoint(9+24-6,12+36);
  f1[5]->SetNextPoint(3+24-6,12+36);
  f1[5]->SetNextPoint(3+24-6,10+36);
  f1[5]->SetNextPoint(0+24-6,10+36);
  f1[5]->SetNextPoint(0+24-6,0+36);
  
  f1[6]=new TPolyLine(7);
  f1[6]->SetNextPoint(0,12);
  f1[6]->SetNextPoint(9,12);
  f1[6]->SetNextPoint(9,22);
  f1[6]->SetNextPoint(6,22);
  f1[6]->SetNextPoint(6,24);
  f1[6]->SetNextPoint(0,24);
  f1[6]->SetNextPoint(0,12);
  
  f1[7]=new TPolyLine(5);
  f1[7]->SetNextPoint(1,22);
  f1[7]->SetNextPoint(3,22);
  f1[7]->SetNextPoint(3,23);
  f1[7]->SetNextPoint(1,23);
  f1[7]->SetNextPoint(1,22);
  
  f1[8]=new TPolyLine(7);
  f1[8]->SetNextPoint(0+12-3,12+12);
  f1[8]->SetNextPoint(9+12-3,12+12);
  f1[8]->SetNextPoint(9+12-3,22+12);
  f1[8]->SetNextPoint(6+12-3,22+12);
  f1[8]->SetNextPoint(6+12-3,24+12);
  f1[8]->SetNextPoint(0+12-3,24+12);
  f1[8]->SetNextPoint(0+12-3,12+12);
  
  f1[9]=new TPolyLine(5);
  f1[9]->SetNextPoint(1+12-3,22+12);
  f1[9]->SetNextPoint(3+12-3,22+12);
  f1[9]->SetNextPoint(3+12-3,23+12);
  f1[9]->SetNextPoint(1+12-3,23+12);
  f1[9]->SetNextPoint(1+12-3,22+12);
  
  f1[10]=new TPolyLine(7);
  f1[10]->SetNextPoint(0+36-9,12+24);
  f1[10]->SetNextPoint(9+36-9,12+24);
  f1[10]->SetNextPoint(9+36-9,22+24);
  f1[10]->SetNextPoint(6+36-9,22+24);
  f1[10]->SetNextPoint(6+36-9,24+24);
  f1[10]->SetNextPoint(0+36-9,24+24);
  f1[10]->SetNextPoint(0+36-9,12+24);
  
  f1[11]=new TPolyLine(5);
  f1[11]->SetNextPoint(1+36-9,22+24);
  f1[11]->SetNextPoint(3+36-9,22+24);
  f1[11]->SetNextPoint(3+36-9,23+24);
  f1[11]->SetNextPoint(1+36-9,23+24);
  f1[11]->SetNextPoint(1+36-9,22+24);
  
  f1[12]=new TPolyLine(11);
  f1[12]->SetNextPoint(0+12-3,12+24);
  f1[12]->SetNextPoint(9+12-3,12+24);
  f1[12]->SetNextPoint(9+12-3,22+24);
  f1[12]->SetNextPoint(8+12-3,22+24);
  f1[12]->SetNextPoint(8+12-3,23+24);
  f1[12]->SetNextPoint(7+12-3,23+24);
  f1[12]->SetNextPoint(7+12-3,22+24);
  f1[12]->SetNextPoint(6+12-3,22+24);    
  f1[12]->SetNextPoint(6+12-3,24+24);
  f1[12]->SetNextPoint(0+12-3,24+24);
  f1[12]->SetNextPoint(0+12-3,12+24);
  
  f1[13]=new TPolyLine(5);
  f1[13]->SetNextPoint(1+12-3,22+24);
  f1[13]->SetNextPoint(3+12-3,22+24);
  f1[13]->SetNextPoint(3+12-3,23+24);
  f1[13]->SetNextPoint(1+12-3,23+24);
  f1[13]->SetNextPoint(1+12-3,22+24);
  
  f1[14]=new TPolyLine(9);
  f1[14]->SetNextPoint(24-6,12);
  f1[14]->SetNextPoint(33-6,12);
  f1[14]->SetNextPoint(33-6,23);
  f1[14]->SetNextPoint(31-6,23);
  f1[14]->SetNextPoint(31-6,24);
  f1[14]->SetNextPoint(27-6,24);
  f1[14]->SetNextPoint(27-6,22);
  f1[14]->SetNextPoint(24-6,22);
  f1[14]->SetNextPoint(24-6,12);
  
  f1[15]=new TPolyLine(9);
  f1[15]->SetNextPoint(24+12-9,12);
  f1[15]->SetNextPoint(33+12-9,12);
  f1[15]->SetNextPoint(33+12-9,23);
  f1[15]->SetNextPoint(31+12-9,23);
  f1[15]->SetNextPoint(31+12-9,24);
  f1[15]->SetNextPoint(27+12-9,24);
  f1[15]->SetNextPoint(27+12-9,22);
  f1[15]->SetNextPoint(24+12-9,22);
  f1[15]->SetNextPoint(24+12-9,12);
  
  
  f1[16]=new TPolyLine(13);
  f1[16]->SetNextPoint(24-6,24);
  f1[16]->SetNextPoint(33-6,24);
  f1[16]->SetNextPoint(33-6,32);
  f1[16]->SetNextPoint(30-6,32);
  f1[16]->SetNextPoint(30-6,34);
  f1[16]->SetNextPoint(31-6,34);
  f1[16]->SetNextPoint(31-6,35);
  f1[16]->SetNextPoint(33-6,35);
  f1[16]->SetNextPoint(33-6,36);
  f1[16]->SetNextPoint(30-6,36);
  f1[16]->SetNextPoint(30-6,34);
  f1[16]->SetNextPoint(24-6,34);
  f1[16]->SetNextPoint(24-6,24);
  
  
  f1[17]=new TPolyLine(7);
  f1[17]->SetNextPoint(36-9,24);
  f1[17]->SetNextPoint(45-9,24);
  f1[17]->SetNextPoint(45-9,34);
  f1[17]->SetNextPoint(39-9,34);
  f1[17]->SetNextPoint(39-9,32);
  f1[17]->SetNextPoint(36-9,32);
  f1[17]->SetNextPoint(36-9,24);
  
  
  f1[18]=new TPolyLine(7);
  f1[18]->SetNextPoint(36-9,34);
  f1[18]->SetNextPoint(37-9,34);
  f1[18]->SetNextPoint(37-9,35);
  f1[18]->SetNextPoint(39-9,35);
  f1[18]->SetNextPoint(39-9,36);
  f1[18]->SetNextPoint(36-9,36);
  f1[18]->SetNextPoint(36-9,34);
  
  f1[19]=new TPolyLine(9);
  f1[19]->SetNextPoint(24-6,0);
  f1[19]->SetNextPoint(30-6,0);
  f1[19]->SetNextPoint(30-6,12);
  f1[19]->SetNextPoint(27-6,12);
  f1[19]->SetNextPoint(27-6,11);
  f1[19]->SetNextPoint(25-6,11);
  f1[19]->SetNextPoint(25-6,12);
  f1[19]->SetNextPoint(24-6,12);
  f1[19]->SetNextPoint(24-6,0);
  
  
  f1[20]=new TPolyLine(7);
  f1[20]->SetNextPoint(39-9,0);
  f1[20]->SetNextPoint(45-9,0);
  f1[20]->SetNextPoint(45-9,11);
  f1[20]->SetNextPoint(43-9,11);
  f1[20]->SetNextPoint(43-9,12);
  f1[20]->SetNextPoint(39-9,12);
  f1[20]->SetNextPoint(39-9,0);

  //Adding pps channels
  f1[21]=new TPolyLine(5);
  f1[21]->SetNextPoint(1+24-6,12+36);
  f1[21]->SetNextPoint(2+24-6,12+36);
  f1[21]->SetNextPoint(2+24-6,12+36-1);
  f1[21]->SetNextPoint(1+24-6,12+36-1);
  f1[21]->SetNextPoint(1+24-6,12+36);

  f1[22]=new TPolyLine(5);
  f1[22]->SetNextPoint(1,12+24);
  f1[22]->SetNextPoint(2,12+24);
  f1[22]->SetNextPoint(2,12+24-1);
  f1[22]->SetNextPoint(1,12+24-1);
  f1[22]->SetNextPoint(1,12+24);
  

  for (Int_t i=0;i<23;i++) {
      f1[i]->SetLineColor(2);
      f1[i]->SetLineWidth(3);
  }
  
}

//...........................................................

//EOF
