/**
 * \file src/CaloLevel0.cpp
 * \author Emiliano Mocchiutti
**/
//
// C/C++ headers
//
#include <sstream>
#include <fstream>
//
// ROOT headers
//
#include <TTree.h>
#include <TBranch.h>
#include <TFile.h>
#include <TObject.h>
//
// YODA headers
//
#include <PamelaRun.h>
#include <physics/calorimeter/CalorimeterEvent.h>
#include <CalibCalPedEvent.h>
//
//
//
#include <GLTables.h>
//
// this package headers
//
#include <delay.h>
#include <CaloLevel0.h>
//
//
// Declaration of the core fortran routines
//
#define calol2cm calol2cm_
extern "C" int calol2cm();
#define calol2tr calol2tr_
extern "C" int calol2tr();
//
using namespace std;
//
//
// Public methods
//

CaloLevel0::~CaloLevel0(){
  if ( de ) delete de;
  delete this;
}

CaloLevel0::CaloLevel0(){
  //
  extern struct FlCaLevel1 clevel1_;
  extern struct FlCaLevel2 clevel2_;
  clevel1 = &clevel1_;
  clevel2 = &clevel2_;
  //
//  extern struct FlEventi eventi_;
//   extern struct FlGruppo gruppo_;
//   extern struct FlGruppo2 gruppo2_;
//   extern struct FlGruppo4 gruppo4_;
//   extern struct FlTaglioen taglioen_;
//   extern struct FlAngolo angolo_;
//   extern struct FlWhere where_;
//   extern struct FlGeneral general_;
//   extern struct FlCh ch_;
//   extern struct FlCalofit calofit_;
//   extern struct FlPawcd pawcd_;
//   extern struct FlQuestd questd_;
//   eventi = &eventi_;
//   gruppo = &gruppo_;
//   gruppo2 = &gruppo2_;
//   gruppo4 = &gruppo4_;
//   taglioen = &taglioen_;
//   angolo = &angolo_;
//   where = &where_;
//   general = &general_;
//   ch = &ch_;
//   calofit = &calofit_;
//   pawcd = &pawcd_;
//   questd = &questd_;
  //
  trkseqno = 0;
  ClearStructs();
  //
  memset(dexy, 0, 2*22*96*sizeof(Float_t));
  memset(dexyc, 0, 2*22*96*sizeof(Float_t));
  memset(mip, 0, 2*22*96*sizeof(Float_t));
  memset(base, 0, 2*22*6*sizeof(Float_t));
  memset(sbase, 0, 2*22*6*sizeof(Float_t));
  memset(obadmask, 0, 2*22*96*sizeof(Int_t));
  memset(obadpulsemask, 0, 2*22*6*sizeof(Int_t));
  memset(ctprecor, 0, 2*22*6*sizeof(Float_t));
  memset(ctsicor, 0, 2*22*9*sizeof(Float_t));
  memset(ctneigcor, 0, 2*22*6*sizeof(Float_t));
  calopar1 = true;
  calopar2 = true;
  calopar3 = true;
  calopar4 = true;
  calopar5 = true;
  crosst = true;
  mask18 = false;
  ftcalopar1 = 0;
  ttcalopar1 = 0;
  ftcalopar2 = 0;
  ttcalopar2 = 0;
  ftcalopar3 = 0;
  ttcalopar3 = 0;
  ftcalopar4 = 0;
  ttcalopar4 = 0;
  ftcalopar5 = 0;
  ttcalopar5 = 0;
}

void CaloLevel0::SetCrossTalk(Bool_t ct){
  crosst = ct;
}

void CaloLevel0::SetCrossTalkType(Bool_t ct){
  ctground = ct;
}

void CaloLevel0::SetCrossTalkType(Int_t ct){
  if ( ct == 0 ) ctground = true;
  if ( ct == 1 ){
    ctground = false;
    noselfct = false;
  };
  if ( ct == 2 ){
    ctground = false;
    noselfct = true;
  };
}

void CaloLevel0::SetVerbose(Bool_t ct){
  verbose = ct;
}

/**
 * Initialize CaloLevel0 object
**/
void CaloLevel0::ProcessingInit(TSQLServer *dbc, UInt_t hs, Int_t &sgnl, TTree *l0tree, Bool_t isdeb, Bool_t isverb){
  if ( !dbc->IsConnected() ) throw -116;  
  this->InitDo(dbc,hs,sgnl,l0tree,isdeb,isverb);
}

/**
 * Initialize CaloLevel0 object
**/
void CaloLevel0::ProcessingInit(GL_TABLES *glt, UInt_t hs, Int_t &sgnl, TTree *l0tree, Bool_t isdeb, Bool_t isverb){
  //
  const TString host = glt->CGetHost();
  const TString user = glt->CGetUser();
  const TString psw = glt->CGetPsw();
  TSQLServer *dbc = TSQLServer::Connect(host.Data(),user.Data(),psw.Data());
  if ( !dbc->IsConnected() ) throw -116;  
  this->InitDo(dbc,hs,sgnl,l0tree,isdeb,isverb);
  dbc->Close();
  delete dbc;
}


void CaloLevel0::InitDo(TSQLServer *dbc, UInt_t hs, Int_t &sgnl, TTree *l0tree, Bool_t isdeb, Bool_t isverb){
  stringstream myquery;
  myquery.str("");
  myquery << "SET time_zone='+0:00'";
  dbc->Query(myquery.str().c_str());
  //
  debug = isdeb;
  verbose = isverb;
  //
  l0tr=(TTree*)l0tree;
  de = new pamela::calorimeter::CalorimeterEvent();
  l0calo = (TBranch*)l0tr->GetBranch("Calorimeter");
  l0tr->SetBranchAddress("Calorimeter", &de);
  //
  trkseqno = 0;
  ClearStructs();
  //
  GL_CALO_CALIB *glcalo = new GL_CALO_CALIB();
  //
  sgnl = 0;
  UInt_t uptime = 0;
  //
  for (Int_t s = 0; s < 4; s++){
    idcalib[s] = 0;
    fromtime[s] = 0;
    totime[s] = 0;
    calibno[s] = 0;
    ClearCalibVals(s);
    //
    sgnl = glcalo->Query_GL_CALO_CALIB(hs,uptime,s,dbc);
    if ( sgnl < 0 ){
	if ( verbose ) printf(" CALORIMETER - ERROR: error from GLTables\n");
	return;
    };
    //  
    idcalib[s] = glcalo->ID_ROOT_L0;
    fromtime[s] = glcalo->FROM_TIME;
    if ( glcalo->TO_TIME < hs ){ // calibration is corrupted and we are using the one that preceed the good one
      totime[s] = uptime;
    } else {
      totime[s] = glcalo->TO_TIME;
    };
    calibno[s] = glcalo->EV_ROOT;
    //
    if ( totime[s] == 0 ){
      if ( verbose ) printf(" CALORIMETER - WARNING: data with no associated calibration\n");
      ClearCalibVals(s);
      sgnl = 100;      
    };
  };
  //
  // determine path and name and entry of the calibration file
  //
  GL_ROOT *glroot = new GL_ROOT();  
  if ( verbose ) printf("\n");
  for (Int_t s = 0; s < 4; s++){
    if ( verbose ) printf(" ** SECTION %i **\n",s);
    if ( totime[s] > 0 ){
      //
      sgnl = glroot->Query_GL_ROOT(idcalib[s],dbc);
      if ( sgnl < 0 ){
	if ( verbose ) printf(" CALORIMETER - ERROR: error from GLTables\n");
	return;
      };
      //	
      stringstream name;
      name.str("");
      name << glroot->PATH.Data() << "/";
      name << glroot->NAME.Data();
      //
      fcalname[s] = (TString)name.str().c_str();
      if ( verbose ) printf(" - runheader at time %u. From time %u to time %u \n   use file %s \n   calibration at entry %i \n\n",hs,fromtime[s],totime[s],fcalname[s].Data(),calibno[s]);
    } else {
      if ( verbose ) printf(" - runheader at time %u. NO CALIBRATION INCLUDE THE RUNHEADER! ",hs);
    };
    sgnl = LoadCalib(s);
    if ( sgnl ) break;
  };    
  //
  delete glcalo;
  delete glroot;
  //
  return;
  //
}

Int_t CaloLevel0::ChkCalib(GL_TABLES *glt, UInt_t atime){
  Int_t sgnl = 0;
  for ( Int_t s = 0; s < 4; s++){
    if ( atime > totime[s] ){
      sgnl = Update(glt,atime,s);
      if ( sgnl < 0 ) return(sgnl); 
    };
  };
  return(sgnl);
}

Int_t CaloLevel0::ChkParam(TSQLServer *dbc, UInt_t runheader, Bool_t mechal){
  Int_t sig = this->ChkParamDo(dbc,runheader,mechal);
  return(sig);
}

Int_t CaloLevel0::ChkParam(GL_TABLES *glt, UInt_t runheader, Bool_t mechal){
  const TString host = glt->CGetHost();
  const TString user = glt->CGetUser();
  const TString psw = glt->CGetPsw();
  TSQLServer *dbc = TSQLServer::Connect(host.Data(),user.Data(),psw.Data());
  if ( !dbc->IsConnected() ) throw -116;
  stringstream myquery;
  myquery.str("");
  myquery << "SET time_zone='+0:00'";
  dbc->Query(myquery.str().c_str());
  //
  Int_t sig = this->ChkParamDo(dbc,runheader,mechal);
  dbc->Close();
  delete dbc;
  return(sig);
}

Int_t CaloLevel0::ChkParamDo(TSQLServer *dbc, UInt_t runheader, Bool_t mechal){
  //
  stringstream calfile;
  stringstream bmfile;
  stringstream aligfile;
  Int_t error = 0;
  FILE *f = 0;
  ifstream badfile;
  GL_PARAM *glparam = new GL_PARAM();
  //
  if ( calopar1 || ( ttcalopar1 != 0 && ttcalopar1 < runheader ) ){
    //
    if ( debug ) printf(" calopar1 %i ftcalopar1 %u ttcalopar1 %u runheader %u \n",calopar1,ftcalopar1,ttcalopar1,runheader);
    //
    if ( calopar1 ){
      //
      // determine where I can find calorimeter ADC to MIP conversion file  
      //
      if ( verbose ) printf(" Querying DB for calorimeter parameters files...\n");
      //
      error = 0;
      error = glparam->Query_GL_PARAM(runheader,101,dbc);
      if ( error < 0 ) return(error);
      //
      calfile.str("");
      calfile << glparam->PATH.Data() << "/";
      calfile << glparam->NAME.Data();
      //
      if ( verbose ) printf("\n Using ADC to MIP conversion file: \n %s \n",calfile.str().c_str());
      f = fopen(calfile.str().c_str(),"rb");
      if ( !f ){
	if ( verbose ) printf(" CALORIMETER - ERROR: no ADC to MIP file!\n");
	return(-105);
      };
      //
      for (Int_t m = 0; m < 2 ; m++ ){
	for (Int_t k = 0; k < 22; k++ ){
	  for (Int_t l = 0; l < 96; l++ ){
	    fread(&mip[m][k][l],sizeof(mip[m][k][l]),1,f);
	    if ( debug ) printf(" %f \n",mip[m][k][l]);
	  };
	};
      };
      fclose(f);      
    };
    //
    calopar1 = false;
    //
    // flight extra corrections:
    //
    if ( verbose ) printf(" Querying DB for calorimeter flight ADC to MIP files...\n");
    //
    error = 0;
    error = glparam->Query_GL_PARAM(runheader,110,dbc);
    if ( error < 0 ) return(error);
    //
    calfile.str("");
    calfile << glparam->PATH.Data() << "/";
    calfile << glparam->NAME.Data();
    ftcalopar1 = glparam->FROM_TIME;
    ttcalopar1 = glparam->TO_TIME;
    //
    if ( verbose ) printf("\n Using ADC to MIP special conversion file: \n %s \n",calfile.str().c_str());
    ifstream spfile;
    spfile.open(calfile.str().c_str());
    if ( !spfile ){
      if ( verbose ) printf(" CALORIMETER - ERROR: no special calibration file!\n");
      return(-123);
    };
    //  
    Int_t vview = 0;
    Int_t vplane = 0;
    Int_t vstrip = 0;
    Float_t vval = 0.;
    while ( spfile >> vview && spfile >> vplane && spfile >> vstrip && spfile >> vval){
      if ( debug ) printf(" Setting ADC to MIP conversion factor: view %i plane %i strip %i mip %f  \n",vview,vplane,vstrip,vval);
      mip[vview][vplane][vstrip] = vval;
    }; 
    //
  };
  //
  //
  if ( calopar2 || ( ttcalopar2 != 0 && ttcalopar2 < runheader ) ){
    //
    if ( debug ) printf(" calopar2 %i ftcalopar2 %u ttcalopar2 %u runheader %u \n",calopar2,ftcalopar2,ttcalopar2,runheader);
    calopar2 = false;
    //
    // determine where I can find calorimeter alignment file  
    //
    //
    error = 0;
    error = glparam->Query_GL_PARAM(runheader,102,dbc);
    if ( error < 0 ) return(error);
    //
    aligfile.str("");
    aligfile << glparam->PATH.Data() << "/";
    aligfile << glparam->NAME.Data();
    ftcalopar2 = glparam->FROM_TIME;
    ttcalopar2 = glparam->TO_TIME;
    //
    if ( verbose ) printf("\n Using parameter file: \n %s \n",aligfile.str().c_str());
    f = fopen(aligfile.str().c_str(),"rb");
    if ( !f ){
      if ( verbose ) printf(" CALORIMETER - ERROR: no parameter file!\n");
      return(-106);
    };
    //
    if ( !mechal ){
      //
      fread(&clevel1->xalig,sizeof(clevel1->xalig),1,f);
      if ( debug ) printf(" xalig = %f \n",clevel1->xalig);
      fread(&clevel1->yalig,sizeof(clevel1->yalig),1,f);
      if ( debug ) printf(" yalig = %f \n",clevel1->yalig);
      fread(&clevel1->zalig,sizeof(clevel1->zalig),1,f);
      if ( debug ) printf(" zalig = %f \n",clevel1->zalig);
    } else {
      if ( verbose ) printf("\n Using MECHANICAL alignement parameters \n");
      //
      CaloStrip cs = CaloStrip();
      cs.UseMechanicalAlig();
      clevel1->xalig = cs.GetXalig();
      if ( debug ) printf(" xalig = %f \n",clevel1->xalig);
      clevel1->yalig = cs.GetYalig();
      if ( debug ) printf(" yalig = %f \n",clevel1->yalig);
      clevel1->zalig = cs.GetZalig();
      if ( debug ) printf(" zalig = %f \n",clevel1->zalig);
      //
      Float_t tmp = 0;
      fread(&tmp,sizeof(clevel1->xalig),1,f);
      fread(&tmp,sizeof(clevel1->yalig),1,f);
      fread(&tmp,sizeof(clevel1->zalig),1,f);
      //      clevel1->zalig = -265.82;
      //    
    };
    fread(&clevel1->emin,sizeof(clevel1->emin),1,f);  
    if ( debug ) printf(" signal threshold = %f \n",clevel1->emin);
    //
    fclose(f);
  };
  //
  // Load offline bad strip mask 
  //
  if ( calopar3 || ( ttcalopar3 != 0 && ttcalopar3 < runheader ) ){
    if ( debug ) printf(" calopar3 %i ftcalopar3 %u ttcalopar3 %u runheader %u \n",calopar3,ftcalopar3,ttcalopar3,runheader);
    calopar3 = false;
    //
    // determine where I can find calorimeter alignment file  
    //
    //
    error = 0;
    error = glparam->Query_GL_PARAM(runheader,103,dbc);
    if ( error < 0 ) return(error);
    //
    bmfile.str("");
    bmfile << glparam->PATH.Data() << "/";
    bmfile << glparam->NAME.Data();
    ftcalopar3 = glparam->FROM_TIME;
    ttcalopar3 = glparam->TO_TIME;
    //
    if ( verbose ) printf("\n Using bad strip offline mask file: \n %s \n\n",bmfile.str().c_str());
    badfile.open(bmfile.str().c_str());
    if ( !badfile ){
      if ( verbose ) printf(" CALORIMETER - ERROR: no bad strip offline mask file!\n");
      return(-115);
    };
    //
    Bool_t isdone = false;
    Int_t bad = 0;
    Int_t view = 1;
    Int_t strip = 0;
    Int_t plane = 21;
    while ( !isdone ) {
      badfile >> bad;
      obadmask[view][plane][strip] = bad;
      if ( debug && bad ) printf(" SETTING view %i plane %i strip %i  BAD = %i \n",view,plane,strip,bad);
      strip++;
      if ( strip > 95 ){
	strip = 0;
	plane--;
	if ( plane < 0 ){
	  plane = 21;
	  view--;
	};
	if ( view < 0 ) isdone = true;
      };
    };
    //
    badfile.close();
  };
  //
  // calopar4
  //
  if ( calopar4 || ( ttcalopar4 != 0 && ttcalopar4 < runheader ) ){
    //
    if ( debug ) printf(" calopar4 %i ftcalopar4 %u ttcalopar4 %u runheader %u \n",calopar4,ftcalopar4,ttcalopar4,runheader);
    //
    calopar4 = false;
    //
    // flight extra corrections:
    //
    if ( verbose ) printf(" Querying DB for calorimeter max rms file...\n");
    //
    error = 0;
    error = glparam->Query_GL_PARAM(runheader,109,dbc);
    if ( error < 0 ) return(error);
    //
    calfile.str("");
    calfile << glparam->PATH.Data() << "/";
    calfile << glparam->NAME.Data();
    ftcalopar4 = glparam->FROM_TIME;
    ttcalopar4 = glparam->TO_TIME;
    //
    if ( verbose ) printf("\n Using calorimeter max rms file: \n %s \n",calfile.str().c_str());
    ifstream spfile;
    spfile.open(calfile.str().c_str());
    if ( !spfile ){
      if ( verbose ) printf(" CALORIMETER - ERROR: no max rms file!\n");
      return(-124);
    };
    //  
    Int_t vview = 0;
    Int_t vplane = 0;
    Int_t vval = 0;
    for (Int_t l=0; l<2; l++){
      for (Int_t m=0; m<22; m++){
	maxrms[l][m] = 26;
      };
    };
    while ( spfile >> vview && spfile >> vplane && spfile >> vval){
      if ( debug ) printf(" Setting view %i plane %i max rms %i  \n",vview,vplane,vval);
      maxrms[vview][vplane] = vval;
    }; 
    spfile.close();
    //
  };
  //
  // calopar5
  //
  if ( calopar5 || ( ttcalopar5 != 0 && ttcalopar5 < runheader ) ){
    //
    if ( debug ) printf(" calopar5 %i ftcalopar5 %u ttcalopar5 %u runheader %u \n",calopar5,ftcalopar5,ttcalopar5,runheader);
    //
    calopar5 = false;
    //
    // flight extra corrections:
    //
    if ( verbose ) printf(" Querying DB for calorimeter noise to signal threshold file...\n");
    //
    error = 0;
    error = glparam->Query_GL_PARAM(runheader,111,dbc);
    if ( error < 0 ) return(error);
    //
    calfile.str("");
    calfile << glparam->PATH.Data() << "/";
    calfile << glparam->NAME.Data();
    ftcalopar5 = glparam->FROM_TIME;
    ttcalopar5 = glparam->TO_TIME;
    //
    if ( verbose ) printf("\n Using calorimeter noise to signal threshold file: \n %s \n",calfile.str().c_str());
    ifstream spfile;
    spfile.open(calfile.str().c_str());
    if ( !spfile ){
      if ( verbose ) printf(" CALORIMETER - ERROR: no noise to signal threshold file!\n");
      return(-125);
    };
    //  
    Int_t vview = 0;
    Int_t vplane = 0;
    Int_t vstrip = 0;
    Float_t vval = 0.;
    for (Int_t l=0; l<2; l++){
      for (Int_t m=0; m<22; m++){
	for (Int_t n=0; n<96; n++){
	  memin[l][m][n] = 0.7;
	};
      };
    };
    while ( spfile >> vview && spfile >> vplane && spfile >> vstrip && spfile >> vval){
      if ( vstrip == -1 ){
	for (Int_t ll=0; ll<96; ll++){
	  if ( debug ) printf(" Setting view %i plane %i strip %i noise to signal ratio %f  \n",vview,vplane,ll,vval);
	  memin[vview][vplane][ll] = vval;
	};
      } else {
	if ( debug ) printf(" Setting view %i plane %i strip %i noise to signal ratio %f  \n",vview,vplane,vstrip,vval);
	memin[vview][vplane][vstrip] = vval;
      };
    }; 
    spfile.close();
    //
  };
  //
  //
  delete glparam;
  //
  return(0);
}

Int_t CaloLevel0::CalcCrossTalkCorr(TSQLServer *dbc, UInt_t runheader, Bool_t ctusetable){
  Int_t sig = CalcCrossTalkCorrDo(dbc,runheader,ctusetable);
  return(sig);  
};

Int_t CaloLevel0::CalcCrossTalkCorr(TSQLServer *dbc, UInt_t runheader){
  Int_t sig = CalcCrossTalkCorrDo(dbc,runheader,true);
  return(sig);
}

Int_t CaloLevel0::CalcCrossTalkCorr(GL_TABLES *glt, UInt_t runheader, Bool_t usetable){
  const TString host = glt->CGetHost();
  const TString user = glt->CGetUser();
  const TString psw = glt->CGetPsw();
  TSQLServer *dbc = TSQLServer::Connect(host.Data(),user.Data(),psw.Data());
  if ( !dbc->IsConnected() ) throw -116;
  stringstream myquery;
  myquery.str("");
  myquery << "SET time_zone='+0:00'";
  dbc->Query(myquery.str().c_str());
  //
  Int_t sig = CalcCrossTalkCorrDo(dbc,runheader,usetable);
  dbc->Close();
  delete dbc;
  //
  return(sig);
  //  
};

Int_t CaloLevel0::CalcCrossTalkCorr(GL_TABLES *glt, UInt_t runheader){
  const TString host = glt->CGetHost();
  const TString user = glt->CGetUser();
  const TString psw = glt->CGetPsw();
  TSQLServer *dbc = TSQLServer::Connect(host.Data(),user.Data(),psw.Data());
  if ( !dbc->IsConnected() ) throw -116;
  stringstream myquery;
  myquery.str("");
  myquery << "SET time_zone='+0:00'";
  dbc->Query(myquery.str().c_str());
  //
  Int_t sig = CalcCrossTalkCorrDo(dbc,runheader,true);
  dbc->Close();
  delete dbc;
  //
  return(sig);
  //
}

Int_t CaloLevel0::CalcCrossTalkCorrDo(TSQLServer *dbc, UInt_t runheader, Bool_t usetable){
  //
  if ( ctground ) return(0);
  //
  Int_t error = 0;
  GL_PARAM *glparam = new GL_PARAM();  
  //
  // determine where I can find file with offline bad pulser mask 
  //
  stringstream bmfile;
  error = 0;
  error = glparam->Query_GL_PARAM(runheader,105,dbc);
  if ( error < 0 ) return(error);
  //
  bmfile.str("");
  bmfile << glparam->PATH.Data() << "/";
  bmfile << glparam->NAME.Data();
  //
  ifstream badfile;
  if ( verbose ) printf("\n Using bad pulser offline mask file: \n %s \n\n",bmfile.str().c_str());
  badfile.open(bmfile.str().c_str());
  if ( !badfile ){
    if ( verbose ) printf(" CALORIMETER - ERROR: no bad pulser offline mask file!\n");
    return(-115);
  };
  //
  Bool_t isdone = false;
  Int_t bad = 0;
  Int_t view = 1;
  Int_t pre = 0;
  Int_t plane = 21;
  while ( !isdone ) {
    badfile >> bad;
    obadpulsemask[view][plane][pre] = bad;
    if ( debug && bad ) printf(" SETTING view %i plane %i pre %i  BAD = %i \n",view,plane,pre,bad);
    pre++;
    if ( pre > 5 ){
      pre = 0;
      plane--;
      if ( plane < 0 ){
	plane = 21;
	view--;
      };
      if ( view < 0 ) isdone = true;
    };
  };
  //
  badfile.close();
  if ( !usetable ){
    //
    // Let's start with cross-talk correction calculation
    //
    GL_CALOPULSE_CALIB *glp = new GL_CALOPULSE_CALIB();
    Float_t adcp[2][22][96];
    Float_t adcpcal[2][22][96];
    memset(adcp , 0, 2*22*96*sizeof(Float_t));
    memset(adcpcal , 0, 2*22*96*sizeof(Float_t));
    //
    UInt_t pampli = 0;  
    for (Int_t s=0; s<4; s++){
      //
      // Save into matrix adcp the values of the highest pulse calibration (pulse amplitude = 2)
      //
      pampli = 2;
      error = 0;
      error = glp->Query_GL_CALOPULSE_CALIB(runheader,s,pampli,dbc);
      if ( error < 0 ){
	if ( verbose ) printf(" CALORIMETER - ERROR: error from GLTables\n");
	return(error);
      };
      //
      UInt_t idcalib = glp->ID_ROOT_L0;
      UInt_t fromtime = glp->FROM_TIME;
      UInt_t calibno = glp->EV_ROOT;
      //
      // determine path and name and entry of the calibration file
      //
      GL_ROOT *glroot = new GL_ROOT();  
      if ( verbose ) printf("\n");
      if ( verbose ) printf(" ** SECTION %i **\n",s);
      //
      error = 0;
      error = glroot->Query_GL_ROOT(idcalib,dbc);
      if ( error < 0 ){
	if ( verbose ) printf(" CALORIMETER - ERROR: error from GLTables\n");
	return(error);
      };
      //	
      stringstream name;
      name.str("");
      name << glroot->PATH.Data() << "/";
      name << glroot->NAME.Data();
      //
      TString fcalname = (TString)name.str().c_str();
      ifstream myfile;
      myfile.open(fcalname.Data());
      if ( !myfile ){    
	return(-107);
      };
      myfile.close();
      //
      TFile *File = new TFile(fcalname.Data());
      if ( !File ) return(-108);
      TTree *tr = (TTree*)File->Get("CalibCalPulse2");
      if ( !tr ) return(-119);
      //
      TBranch *calo = tr->GetBranch("CalibCalPulse2");
      //
      pamela::CalibCalPulse2Event *ce = 0;
      tr->SetBranchAddress("CalibCalPulse2", &ce);
      //
      Long64_t ncalibs = calo->GetEntries();
      //
      if ( !ncalibs ) return(-110); 
      //
      if ( calo->GetEntry(calibno) <= 0) throw -36;
      if ( verbose ) printf(" PULSE2 using entry %u from file %s",calibno,fcalname.Data());
      //
      // retrieve calibration table
      //
      if ( ce->pstwerr[s] && ce->pperror[s] == 0 && ce->unpackError == 0 ){
	for ( Int_t d=0 ; d<11 ;d++  ){
	  for ( Int_t j=0; j<96 ;j++){
	    if ( s == 2 ){
	      adcp[0][2*d+1][j] = ce->calpuls[3][d][j];
	    };
	    if ( s == 3 ){
	      adcp[0][2*d][j] = ce->calpuls[1][d][j];
	    };
	    if ( s == 0 ){
	      adcp[1][2*d][j] = ce->calpuls[0][d][j];
	    };
	    if ( s == 1 ){
	      adcp[1][2*d+1][j] = ce->calpuls[2][d][j];
	    };
	  };
	};
      } else {
	if ( verbose ) printf(" CALORIMETER - ERROR: problems finding a good calibration in this file! \n\n ");
	return(-111);
      };
      //
      File->Close();
      delete glroot;
      //
      // Save into matrix adcpcal the calibrated values of the pulse calibration (subtraction of pulse amplitude = 0 relative to the pulse2 calibration used)
      //
      pampli = 0;
      error = 0;
      error = glp->Query_GL_CALOPULSE_CALIB(fromtime,s,pampli,dbc);
      if ( error < 0 ){
	if ( verbose ) printf(" CALORIMETER - ERROR: error from GLTables\n");
	return(error);
      };
      //
      idcalib = glp->ID_ROOT_L0;
      calibno = glp->EV_ROOT;
      //
      // determine path and name and entry of the calibration file
      //
      glroot = new GL_ROOT();  
      if ( verbose ) printf("\n");
      if ( verbose ) printf(" ** SECTION %i **\n",s);
      //
      error = 0;
      error = glroot->Query_GL_ROOT(idcalib,dbc);
      if ( error < 0 ){
	if ( verbose ) printf(" CALORIMETER - ERROR: error from GLTables\n");
	return(error);
      };
      //	
      name.str("");
      name << glroot->PATH.Data() << "/";
      name << glroot->NAME.Data();
      //
      fcalname = (TString)name.str().c_str();
      myfile.open(fcalname.Data());
      if ( !myfile ){    
	return(-107);
      };
      myfile.close();
      //
      TFile *File1 = new TFile(fcalname.Data());
      if ( !File1 ) return(-108);
      TTree *tr1 = (TTree*)File1->Get("CalibCalPulse1");
      if ( !tr1 ) return(-120);
      //
      TBranch *calo1 = tr1->GetBranch("CalibCalPulse1");
      //
      pamela::CalibCalPulse1Event *ce1 = 0;
      tr1->SetBranchAddress("CalibCalPulse1", &ce1);
      //
      ncalibs = calo1->GetEntries();
      //
      if ( !ncalibs ) return(-110); 
      //
      if ( calo1->GetEntry(calibno) <= 0 ) throw -36;
      if ( verbose ) printf(" PULSE1 using entry %u from file %s",calibno,fcalname.Data());
      //
      // retrieve calibration table
      //
      if ( ce1->pstwerr[s] && ce1->pperror[s] == 0 && ce1->unpackError == 0 ){
	for ( Int_t d=0 ; d<11 ;d++  ){
	  for ( Int_t j=0; j<96 ;j++){
	    if ( s == 2 ){
	      adcpcal[0][2*d+1][j] = adcp[0][2*d+1][j] - ce1->calpuls[3][d][j];
	    };
	    if ( s == 3 ){
	      adcpcal[0][2*d][j] = adcp[0][2*d][j] - ce1->calpuls[1][d][j];
	    };
	    if ( s == 0 ){
	      adcpcal[1][2*d][j] = adcp[1][2*d][j] - ce1->calpuls[0][d][j];
	    };
	    if ( s == 1 ){
	      adcpcal[1][2*d+1][j] = adcp[1][2*d+1][j] - ce1->calpuls[2][d][j];
	    };
	  };
	};
      } else {
	if ( verbose ) printf(" CALORIMETER - ERROR: problems finding a good calibration in this file! \n\n ");
	return(-111);
      };
      //
      File1->Close();
      //
      delete glroot;
      //
    };// loop on the four sections
    //
    //
    delete glp;
    //
    // Ok, now we can try to calculate the cross-talk correction for each pre-amplifier
    //
    for ( Int_t v=0; v<2; v++){
      if ( debug ) printf(" \n\n NEW VIEW \n");
      for ( Int_t p=0; p<22; p++){
	for ( Int_t npre=0; npre<6; npre++){
	  ctprecor[v][p][npre] = 1000.;
	  ctneigcor[v][p][npre] = 1000.;
	  Int_t str0=npre*16;
	  Int_t str16= -1 + (1+npre)*16;
	  //
	  UInt_t neigc = 0;
	  UInt_t farc = 0;
	  UInt_t pulsc = 0;
	  Float_t sigpulsed = 0.;
	  Float_t neigbase = 0.;
	  Float_t farbase = 0.;
	  //
	  // Loop over the strip of the pre and sum all signal far away from pulsed strip, signal in the neighbour(s) strip(s) and save the pulsed signal
	  // moreover count the number of strips in each case
	  //
	  for (Int_t s=str0; s<=str16; s++){
	    if ( adcpcal[v][p][s] > 10000.){
	      sigpulsed = adcpcal[v][p][s];
	      pulsc++;
	      if ( s > str0 ){
		neigbase += adcpcal[v][p][s-1];
		neigc++;
		farbase -= adcpcal[v][p][s-1];
		farc--;
	      };
	      if ( s < str16 ){
		neigbase += adcpcal[v][p][s+1];
		neigc++;
		farbase -= adcpcal[v][p][s+1];
		farc--;
	      };
	    } else {
	      farc++;
	      farbase += adcpcal[v][p][s];
	    };
	  };
	  //
	  // Now calculate the corrections
	  //
	  Float_t avefarbase = 0.;
	  if ( farc ) avefarbase = farbase/(Float_t)farc;
	  Float_t aveneigbase = 0.;
	  if ( neigc ) aveneigbase = neigbase/(Float_t)neigc;
	  //
	  if ( pulsc == 1 && farc && neigc ){
	    ctprecor[v][p][npre] = -avefarbase/(sigpulsed+fabs(avefarbase));
	    ctneigcor[v][p][npre] = fabs(aveneigbase-avefarbase)/(sigpulsed+fabs(avefarbase));	  
	    if ( debug ) printf(" Cross-talk correction View %i Plane %i Pre %i : pre-correction: %f neighbour strips correction %f \n",v,p,npre,ctprecor[v][p][npre],ctneigcor[v][p][npre]);
	  } else {
	    //
	    // did not find the pulsed strip or more than one pulsed strip found!
	    //
	    if ( debug ) printf(" Problems finding the cross-talk corrections: \n View %i Plane %i Pre %i number of pulsed strip %i \n Average faraway baseline %f number of strips %i Average neighbour baseline %f number of neighbour strips %i \n",v,p,npre,pulsc,avefarbase,farc,aveneigbase,neigc);
	    //
	  };
	};
	if ( debug ) printf(" \n ==================== \n");
      };
    };
  } else {
    //
    // use pre-amply table 
    //    
    //
    // determine where I can find file with offline neighbour correction table
    //
    stringstream bmfile2;
    error = 0;
    error = glparam->Query_GL_PARAM(runheader,106,dbc);
    if ( error < 0 ) return(error);
    //
    bmfile2.str("");
    bmfile2 << glparam->PATH.Data() << "/";
    bmfile2 << glparam->NAME.Data();
    //
    ifstream badfile2;
    if ( verbose ) printf("\n Using pre-amply neighbour crosstalk table file: \n %s \n\n",bmfile2.str().c_str());
    badfile2.open(bmfile2.str().c_str());
    if ( !badfile2 ){
      if ( verbose ) printf(" CALORIMETER - ERROR: no pre-amply neighbour crosstalk table file!\n");
      return(-121);
    };
    //  
    Int_t vview = 0;
    Int_t vplane = 0;
    Int_t vpre = 0;
    Float_t vcorr = 0.;
    while ( badfile2 >> vview && badfile2 >> vplane && badfile2 >> vpre && badfile2 >> vcorr){
      if ( debug ) printf(" Pre-amply neighbour correction: view %i plane %i pre %i correction %f  \n",vview,vplane,vpre,vcorr);
      ctneigcor[vview][vplane][vpre] = vcorr;
    }; 
    //
    // determine where I can find file with offline SECOND neighbour correction table
    //
    stringstream bmfile3;
    error = 0;
    error = glparam->Query_GL_PARAM(runheader,107,dbc);
    if ( error < 0 ) return(error);
    //
    bmfile3.str("");
    bmfile3 << glparam->PATH.Data() << "/";
    bmfile3 << glparam->NAME.Data();
    //
    ifstream badfile3;
    if ( verbose ) printf("\n Using pre-amply second neighbour crosstalk table file: \n %s \n\n",bmfile3.str().c_str());
    badfile3.open(bmfile3.str().c_str());
    if ( !badfile3 ){
      if ( verbose ) printf(" CALORIMETER - ERROR: no pre-amply second neighbour crosstalk table file!\n");
      return(-122);
    };
    //  
    Int_t pview = 0;
    Int_t pplane = 0;
    Int_t ppre = 0;
    Float_t pcorr = 0.;
    while ( badfile3 >> pview && badfile3 >> pplane && badfile3 >> ppre && badfile3 >> pcorr){
      if ( debug ) printf(" Pre-amply second neighbour correction: view %i plane %i pre %i correction %f  \n",pview,pplane,ppre,-pcorr);
      ctprecor[pview][pplane][ppre] = -pcorr; // data are saved as negatives in the file
    }; 
    //
    // determine where to find the file containing the Silicon crosstalk correction table
    //
    stringstream bmfile4;
    error = 0;
    error = glparam->Query_GL_PARAM(runheader,108,dbc);
    if ( error < 0 ) return(error);
    //
    bmfile4.str("");
    bmfile4 << glparam->PATH.Data() << "/";
    bmfile4 << glparam->NAME.Data();
    //
    ifstream badfile4;
    if ( verbose ) printf("\n Using Silicon crosstalk table file: \n %s \n\n",bmfile4.str().c_str());
    badfile4.open(bmfile4.str().c_str());
    if ( !badfile4 ){
      if ( verbose ) printf(" CALORIMETER - ERROR: no Silicon crosstalk table file!\n");
      return(-125);
    };
    //  
    Int_t spview = 0;
    Int_t spplane = 0;
    Int_t psil = 0;
    Float_t spcorr = 0.;
    memset(ctsicor, 0, 2*22*9*sizeof(Float_t));
    while ( badfile4 >> spview && badfile4 >> spplane && badfile4 >> psil && badfile4 >> spcorr){
      if ( debug ) printf(" Silicon correction: view %i plane %i silicon %i correction %f  \n",spview,spplane,psil,-spcorr);
      ctsicor[spview][spplane][psil] = -spcorr; // data are saved as negatives in the file
    }; 
    //
  };
  //
  delete glparam;
  //
  // Check the calculated corrections
  //
  Int_t opre=0;
  Int_t ppre=0;
  Bool_t found = false;
  for ( Int_t v=0; v<2; v++){
    for ( Int_t p=0; p<22; p++){
      for ( Int_t npre=0; npre<6; npre++){
	if ( ctprecor[v][p][npre] == 1000. || ctneigcor[v][p][npre] == 1000. || obadpulsemask[v][p][npre] != 0 ){
	  if ( debug ) printf(" Cross-talk correction CHANGED for view %i Plane %i Pre %i\n    BEFORE: pre-correction: %f neighbour strips correction %f \n",v,p,npre,ctprecor[v][p][npre],ctneigcor[v][p][npre]);
	  if ( npre%2 ){
	    opre = npre-1;
	  } else {
	    opre = npre+1;	    
	  };
	  if ( ctprecor[v][p][opre] == 1000. || ctneigcor[v][p][opre] == 1000. || obadpulsemask[v][p][opre] != 0 ){
	    ppre=0;
	    found = false;
	    while ( ppre < 6 ){
	      if ( ctprecor[v][p][ppre] != 1000. && ctneigcor[v][p][ppre] != 1000. && !obadpulsemask[v][p][ppre] ){
		found = true;
		ctprecor[v][p][npre] = ctprecor[v][p][ppre];
		ctneigcor[v][p][npre] = ctneigcor[v][p][ppre];
		break;
	      };
	      ppre++;
	    };
	    if ( !found ){
	      if ( verbose ) printf(" WARNING: cannot find a good cross-talk correction for view %i plane %i pre %i \n Setting to default values 0.002 0.002\n",v,p,npre);
	      ctprecor[v][p][npre] = 0.002;
	      ctneigcor[v][p][npre] = 0.002;
	    };
	  } else {
	    ctprecor[v][p][npre] = ctprecor[v][p][opre];
	    ctneigcor[v][p][npre] = ctneigcor[v][p][opre];
	  };
	  if ( debug ) printf("    AFTER: pre-correction: %f neighbour strips correction %f \n",ctprecor[v][p][npre],ctneigcor[v][p][npre]);
	};
      };
    };
  };  
  //
  return(0);
}

void CaloLevel0::FindBaseCompress(Int_t l, Int_t m, Int_t pre){
  Int_t n = 0;
  Float_t q = 0;
  this->FindBaseCompress(l,m,pre,n,q);
}

void CaloLevel0::FindBaseCompress(Int_t l, Int_t m, Int_t pre, Int_t &nst, Float_t &qp){
  for (Int_t e = pre*16; e < (pre+1)*16 ; e++){
    dexy[l][m][e] = dexyc[l][m][e];
  };  
  this->FindBaseRaw(l,m,pre,nst,qp);
}

void CaloLevel0::FindBaseRaw(Int_t l, Int_t m, Int_t pre){
  Int_t n = 0;
  Float_t q = 0;
  this->FindBaseRaw(l,m,pre,n,q);
}

void CaloLevel0::FindBaseRaw(Int_t l, Int_t m, Int_t pre, Int_t &nst, Float_t &qp){
  //
  Float_t minstrip = 100000.;
  Float_t rms = 0.;
  Int_t process = 0;
  Int_t onlmask[16];
  memset(onlmask, 0, 16*sizeof(Int_t));
  //
  while ( process < 2 ){
    //
    minstrip = 100000.;
    rms = 0.;
    base[l][m][pre] = 0.;
    qp = 0.;
    //
    Int_t spos = -1;
    Int_t ee = 0;
    for (Int_t e = pre*16; e < (pre+1)*16 ; e++){
      if ( calgood[l][m][e] == 0. && obadmask[l][m][e] == 0 &&  dexy[l][m][e]-calped[l][m][e] < minstrip &&  dexy[l][m][e] > 0. && onlmask[ee] == 0 ) {
	minstrip = dexy[l][m][e]-calped[l][m][e];
	rms = calthr[l][m][pre];
	spos = ee;
      };
      ee++;
      qp += (dexy[l][m][e]-calped[l][m][e]-sbase[l][m][e]);
    };
    //
    if ( debug && l==0 ){
      printf("\n BASELINE CALCULATION for view %i pl %i pre %i: \n => minstrip %f rms %f \n => qp = %f \n",l,m,pre,minstrip,rms,qp);
    };
    if ( minstrip != 100000. ) {
      Float_t strip6s = 0.;
      for (Int_t e = pre*16; e < (pre+1)*16 ; e++){
	if ( (dexy[l][m][e]-calped[l][m][e]) >= minstrip && (dexy[l][m][e]-calped[l][m][e]) <= (minstrip+rms) ) {
	  strip6s += 1.;
	  base[l][m][pre] += (dexy[l][m][e] - calped[l][m][e]);
	};
	//
	//  compression
	//
	//	if ( abs((int)(dexy[l][m][e]-calped[l][m][e])) <= (minstrip+rms) ) {
	//	  dexyc[l][m][e] = 0.;
	//	} else {
	dexyc[l][m][e] = dexy[l][m][e];
	  //	};
      };
      //
      if ( strip6s == 1. && process < 1 ){
	onlmask[spos] = 1;
	process++;
	if ( debug ) printf(" Warning, only one strip to calculate baseline: minstrip %f rms %f spos %i l %i m %i pre %i \n",minstrip,rms,spos,l,m,pre);
	continue;
      };
      process += 2;
      nst = (Int_t)strip6s;
      //
      if ( debug ){
	printf(" strip6s %f \n",strip6s);
      };
      //	if ( strip6s >= 9. ){	    
      if ( (strip6s >= 2. && process == 2) || (strip6s >= 9. && process > 2) ){	    
	//if ( (strip6s >= 4. && process == 2) || (strip6s >= 9. && process > 2) ){	    
	Double_t arro = base[l][m][pre]/strip6s;
	Float_t deci = 1000.*((float)arro - float(int(arro)));		      
	if ( deci < 500. ) {
	  arro = double(int(arro));
	} else {
	  arro = 1. + double(int(arro));
	};
	base[l][m][pre] = arro;
	//
	// if too few strips were used to determine the baseline check if it is comparable with the previous event, if not mark it as bad
	//
	if ( debug && process > 2 ) printf(" AGH low strip value was discarded process %i strip6s %f minstrip %f rms %f spos %i\n",process,strip6s,minstrip,rms,spos);
	if ( debug ) printf(" Calculated baseline: base %f sbase-0.02*qp %f \n",base[l][m][pre],(-qp*0.02+sbase[l][m][pre]));
	//
	if ( strip6s < 4 && base[l][m][pre] > (-0.015*qp+sbase[l][m][pre]) && sbase[l][m][pre] > 0. ){
	  if ( debug ) printf(" Suspicious calculated baseline: base %f sbase-0.02*qp %f strip6s %i \n",base[l][m][pre],(-qp*0.02+sbase[l][m][pre]),(Int_t)strip6s);
	  base[l][m][pre] = 31000.;	
	  for (Int_t e = pre*16; e < (pre+1)*16 ; e++){
	    dexyc[l][m][e] = dexy[l][m][e];
	  };	  
	};
      } else {
	base[l][m][pre] = 31000.;
	for (Int_t e = pre*16; e < (pre+1)*16 ; e++){
	  dexyc[l][m][e] = dexy[l][m][e];
	};
      };
    } else {
      process += 2;
      base[l][m][pre] = 31000.;
      for (Int_t e = pre*16; e < (pre+1)*16 ; e++){
	dexyc[l][m][e] = dexy[l][m][e];
      };
    };
  };
}

Int_t CaloLevel0::Calibrate(Int_t ei){
  //
  // get entry ei
  //
  if ( l0calo->GetEntry(ei) <= 0 ) throw -36;
  //
  // if it was not a selftrigger event, could it ever been a selftrigger event? if so trigty = 3.
  //
  clevel2->nsatstrip = 0.;
  Int_t val = 0;
  Int_t del = 1000;
  for (Int_t sec = 0; sec < 4; sec++){
    for (Int_t dsec = 0; dsec < 7; dsec++){
      val = (Int_t)de->calselftrig[sec][dsec];
      del = delay(val);
      clevel2->selfdelay[sec][dsec] = del;
    };
  };
  val = 0;
  del = 1000;
  if ( clevel2->trigty < 2. ){
    Bool_t ck = false;
    for (Int_t sec = 0; sec < 4; sec++){
      val = (Int_t)de->calselftrig[sec][6];
      del = delay(val);
      if ( del < 1000 ){
	clevel2->wartrig = 0.;      
	clevel2->trigty = 3.;
	ck = true;
	break;
      };
    };
    //    if ( !ck ) clevel2->wartrig = 100.;      
  } else {
    Bool_t ck = false;
    for (Int_t sec = 0; sec < 4; sec++){
      val = (Int_t)de->calselftrig[sec][6];
      del = delay(val);
      if ( del < 1000 ){
	clevel2->wartrig = 0.;      
	ck = true;
      };
    };
    if ( !ck ) clevel2->wartrig = 100.;      
  };
  //
  Int_t se = 5;
  Int_t done = 0;
  Int_t pre = -1; 
  Bool_t isCOMP = false;
  Bool_t isFULL = false;
  Bool_t isRAW = false;
  Float_t ener;
  Int_t doneb = 0;
  Int_t donec = 0;
  Int_t ck[2][22][6];
  memset(ck, 0, 2*22*6*sizeof(Int_t));
  Int_t ipre = 0;
  //  Int_t ip[3] = {0};
  Int_t ip[3] = {0,0,0};
  Int_t ipp = 0;
  Float_t base0, base1, base2;
  base0 = 0.;
  base1 = 0.;
  base2 = 0.;
  Float_t qpre[2][22][6];
  memset(qpre, 0, 2*22*6*sizeof(Float_t));
  Float_t ene[96];
  Int_t chdone[4] = {0,0,0,0};
  Int_t pe = 0;
  //
  Float_t ener0 = 0.;
  Float_t cbase0 = 0.;
  Float_t totbase = 0.;
  Float_t totped = 0.;
  Bool_t pproblem = false;
  Bool_t negbase = false;
  //
  Float_t tim = 0.;
  Int_t plo = 0;
  Int_t fbi = 0;
  Int_t cle = 0;
  //
  // run over views and planes
  //
  for (Int_t l = 0; l < 2; l++){
    for (Int_t m = 0; m < 22; m++){
      //
      // determine the section number   
      //
      negbase = false;
      se = 5;
      if (l == 0 && m%2 == 0) se = 3; 
      if (l == 0 && m%2 != 0) se = 2;
      if (l == 1 && m%2 != 0) se = 1;
      if (l == 1 && m%2 == 0) se = 0;		
      //
      // determine what kind of event we are going to analyze
      //
      isCOMP = false;
      isFULL = false;
      isRAW = false;
      if ( de->stwerr[se] & (1 << 16) ) isCOMP = true; 
      if ( de->stwerr[se] & (1 << 17) ) isFULL = true; 
      if ( de->stwerr[se] & (1 << 3) ) isRAW = true; 
      if ( !chdone[se] ){
	//
	// check for any error in the event
	//
	clevel2->crc[se] = 0;
	if ( de->perror[se] == 132 ){
	  clevel2->crc[se] = 1;
	  pe++;
	};
	clevel2->perr[se] = 0;
	if ( de->perror[se] != 0 ){
	  clevel2->perr[se] = (Int_t)de->perror[se];
	  pe++;
	};
	clevel2->swerr[se] = 0;
	for (Int_t j = 0; j < 7 ; j++){
	  if ( (j != 3) && (de->stwerr[se] & (1 << j)) ){
	    clevel2->swerr[se] = 1; 
	    pe++;
	  };
	};	    
	chdone[se] = 1;
      };
      if ( clevel2->crc[se] == 0 && (clevel1->good2 == 1 || clevel2->trigty >= 2) ){
	pre = -1; 
	//
	for (Int_t nn = 0; nn < 96; nn++){		    
	  //	  ene[nn] = 0.;
	  dexy[l][m][nn] = de->dexy[l][m][nn] ; 
	  dexyc[l][m][nn] = de->dexyc[l][m][nn] ; 
	};
	//
	// run over preamplifiers
	//
	pre = -1;
	cbase0 = 0.;
	Int_t nstt[2];
	Float_t rqp[2];
	for (Int_t i = 0; i < 3; i++){
	  nstt[0] = 1000;
	  nstt[1] = 1000;
	  rqp[0] = 0.;
	  rqp[1] = 0.;
	  for (Int_t j = 0; j < 2; j++){
	    pre = j + i*2;
	    // 
	    // baseline check and calculation
	    //
	    if ( !isRAW ){
	      //
	      // if it is a compress event with fully transmitted pre try to calculate the baseline
	      //
	      if ( de->base[l][m][pre] != 0. && de->base[l][m][pre]<31000. ) {
		base[l][m][pre] = de->base[l][m][pre] ;   
	      } else {
		FindBaseCompress(l,m,pre,nstt[j],rqp[j]);
	      };
	      cbase0 += base[l][m][pre];
	    } else {
	      //
	      // if it is a raw event calculate the baseline. 
	      //
	      FindBaseRaw(l,m,pre,nstt[j],rqp[j]);
	      cbase0 += base[l][m][pre];
	    };
	  };
	  //
	  // if we are able to calculate the baseline with more than 3 strips on one pre and not in the other one choose the pre with more calculated strips
	  //
	  if ( nstt[0] < 4 && nstt[1] >= 4 && nstt[0] != 1000 && nstt[1] != 1000 ) base[l][m][pre-1] = 31000.;
	  if ( nstt[0] >= 4 && nstt[1] < 4 && nstt[0] != 1000 && nstt[1] != 1000 ) base[l][m][pre] = 31000.;
	  // 	  //
	  // 	  // if we are NOT able to calculate the baseline with more than 3 strips on both pres take the baseline (if any) of the one which has less energy
	  // 	  //
	  // 	  if ( nstt[0] < 4 && nstt[1] < 4 ){
	  // 	    if ( rqp[0] >= rqp[1] ) base[l][m][pre-1] = 31000.;
	  // 	    if ( rqp[0] < rqp[1] ) base[l][m][pre] = 31000.;
	  // 	  };
	};
	//
	// run over strips
	//
	pre = -1;
	ener0 = 0.;
	totbase = 0.;
	totped = 0.;
	for (Int_t i = 0 ; i < 3 ; i++){
	  ip[i] = 0;
	  for (Int_t n = i*32 ; n < (i+1)*32 ; n++){		    
	    if (n%16 == 0) {
	      done = 0;
	      doneb = 0;
	      donec = 0;
	      pre++;
	      ck[l][m][pre] = 0;
	      qpre[l][m][pre] = 0.;
	    };
	    // 
	    // baseline check and calculation
	    //
	    // no suitable new baseline, use old ones!
	    //
	    if ( !done ){
	      if ( (base[l][m][pre] == 31000. || base[l][m][pre] == 0.) ){
		ck[l][m][pre] = 1;
		if (pre%2 == 0) {
		  ip[i] = pre + 1;
		} else { 
		  ip[i] = pre - 1;
		};
		if ( (base[l][m][ip[i]] == 31000. || base[l][m][ip[i]] == 0. || !crosst ) ){
		  //
		  ck[l][m][pre] = 2;
		  if ( sbase[l][m][pre] == 31000. || sbase[l][m][pre] == 0. ) {
		    ck[l][m][pre] = 3;
		  };
		};
	      };
	      done = 1;
	    };			
	    //
	    // CALIBRATION ALGORITHM
	    // 
	    if ( !doneb ){
	      if ( debug ) printf(" ck[l][m][pre] is %i \n",ck[l][m][pre]);
	      switch (ck[l][m][pre]) {
	      case 0: 
		base0 = base[l][m][pre];
		base2 = calbase[l][m][pre];
		if ( debug ) printf(" base0 = base l%i m%i pre%i = %f base2 = calbase l m pre = %f \n",l,m,pre,base[l][m][pre],calbase[l][m][pre]);
		break;
	      case 1: 
		base0 = base[l][m][ip[i]];
		base2 = calbase[l][m][ip[i]];
		if ( debug ) printf(" base0 = base l%i m%i ip(i)%i = %f base2 = calbase l m ip(i) = %f \n",l,m,ip[i],base[l][m][ip[i]],calbase[l][m][ip[i]]);
		break;
	      case 2: 
		base0 = sbase[l][m][pre];
		base2 = calbase[l][m][pre];	
		if ( debug ) printf(" base0 = sbase l%i m%i pre%i = %f base2 = calbase l m pre = %f \n",l,m,pre,sbase[l][m][pre],calbase[l][m][pre]);
		break;
	      case 3: 
		base0 = calbase[l][m][pre];
		base2 = calbase[l][m][pre];
		if ( debug ) printf(" base0 = calbase l%i m%i pre%i = %f base2 = calbase l m pre = %f \n",l,m,pre,calbase[l][m][pre],calbase[l][m][pre]);
		break;
	      };
	      base1 = calbase[l][m][pre];
	      doneb = 1;
	    };
	    ener = dexyc[l][m][n];
	    ener0 += ener;
	    clevel1->estrip[n][m][l] = 0.;
	    totbase += de->base[l][m][pre]/96.;
	    totped += fabs(calped[l][m][n]);
	    if ( de->base[l][m][pre] < 0 ) negbase = true;
	    if ( base0>0 && base0 < 30000. ){
	      //
	      // save the baseline only if the energy release is "small"
	      //
	      if ( !donec && (base0 + base1 - base2) != 0. && (n+1)%16==0 ){
		if ( qpre[l][m][pre] < 200. ) sbase[l][m][pre] = base0 + base1 - base2;
		donec = 1;
	      };
	      if ( ener > 0. ){
		clevel1->estrip[n][m][l] = (ener - calped[l][m][n] - base0 - base1 + base2)/mip[l][m][n] ;
		//
		// OK, now in estrip we have the energy deposit in MIP of all the strips for this event (at the end of loops of course)
		//
		if ( clevel1->estrip[n][m][l] > 0. ) qpre[l][m][pre] += clevel1->estrip[n][m][l];
		//
		//
	      };
	    };
	  };
	};
	//
	// check if there were problems with 5.7 or glitches in the power supply
	// 
	//	if ( ((ener0 == 0. && cbase0 == 0.) || negbase || totbase > 196600. || totped < 1. ) && !pproblem && clevel2->perr[se] == 0){	// check pedestal and baseline values for one plane, if all zeros calibration is not valid (calorimeter power problems) [8th data reduction bug, fixed on 25/11/2009 by E.M.]
	if ( ((ener0 == 0. && cbase0 == 0.) || negbase || totbase > 32700. || totped < 1. ) && !pproblem && clevel2->perr[se] == 0){	// check pedestal and baseline values for one plane, if all zeros calibration is not valid (calorimeter power problems) [8th data reduction bug, fixed on 25/11/2009 by E.M.]
	  if ( verbose ) printf(" L0 entry %i : calorimeter power problems! event marked as bad perr %f swerr %X view %i plane %i negbase %i totbase %f totped %f\n",ei,de->perror[se],de->stwerr[se],l,m, negbase, totbase, totped);
	  pproblem = true;
	  pe++;
	};
	//
      } else {
	for (Int_t nn = 0; nn < 96; nn++){		    
	  clevel1->estrip[nn][m][l] = 0.; 
	};
      };
    };
  };
  //
  // run over views and planes to apply crosstalk corrections
  //
  for (Int_t l = 0; l < 2; l++){
    for (Int_t m = 0; m < 22; m++){
      //
      // determine the section number   
      //
      se = 5;
      if (l == 0 && m%2 == 0) se = 3; 
      if (l == 0 && m%2 != 0) se = 2;
      if (l == 1 && m%2 != 0) se = 1;
      if (l == 1 && m%2 == 0) se = 0;		
      //
      // check for any error in the event
      //
      if ( clevel2->crc[se] == 0 && (clevel1->good2 == 1 || clevel2->trigty >= 2) ){
	//
	// Cross-talk corrections  
	//
	if ( crosst ){
	  //
	  // energy on silicon ladders
	  //
	  Float_t qsi[3];
	  qsi[0] = qpre[l][m][0]+qpre[l][m][1];
	  qsi[1] = qpre[l][m][2]+qpre[l][m][3];
	  qsi[2] = qpre[l][m][4]+qpre[l][m][5];	      
	  //
	  for ( pre = 1; pre < 6; pre += 2 ){	
	    Int_t ladder = (pre - 1)/2;
	    //
	    // If the noselfct flag is set the strip doesn't suffer the self crosstalk due to electronics so we must subtract some energy
	    //
	    if ( noselfct ){
	      for (Int_t j = ladder*32 ; j < (ladder+1)*32 ; j++){
		ipre = j/16 ;	
		if ( clevel1->estrip[j][m][l] != 0. ) clevel1->estrip[j][m][l] -=  clevel1->estrip[j][m][l] * ctprecor[l][m][ipre];
	      };
	    };
	    //
	    // Using the neighbour pre baseline
	    //
	    if (ck[l][m][pre] == 1 || ck[l][m][pre-1] == 1){
	      //
	      // pre-amplifier effect on baseline when using the neighbour pre (ck=1)
	      //
	      if (ck[l][m][pre] == 1){
		ipre = pre;
		ipp = pre - 1;
	      } else {
		ipre = pre - 1;
		ipp = pre;
	      };
	      Int_t it = 0;
	      Float_t nqpre = 0.;
              //
              if ( debug ) printf(" CK1 Limit for while: 0.07 \n");
	      for (Int_t j = ipre*16 ; j < (ipre+1)*16 ; j++){
		if ( !ctground ){
		  if ( clevel1->estrip[j][m][l] != 0. ) clevel1->estrip[j][m][l] += - qpre[l][m][ipp] * ctprecor[l][m][ipp];
		} else {
		  if ( clevel1->estrip[j][m][l] != 0. ) clevel1->estrip[j][m][l] += - qpre[l][m][ipp] * 0.00478;
		};
		if ( clevel1->estrip[j][m][l] > 0. ) nqpre += clevel1->estrip[j][m][l] ;
	      };
	      qpre[l][m][ipre] = nqpre;
              nqpre = 0.;
	      Float_t deltaqpre = qpre[l][m][ipre];	      
	      //
	      // these values are empirically determined, usually the routine converge due to deltaqsi and the latest applied correction is based on less than 1 mip
	      //
	      while ( it < 10 && deltaqpre > 0.07 ){
		nqpre = 0.;
		for (Int_t j = ipre*16 ; j < (ipre+1)*16 ; j++){
		  if ( !ctground ){
		    if ( debug ) printf(" CK1 pre correction: iteration %i deltaqpre %f  ctprecor %f  TOTAL CORRECTION %f \n",it,deltaqpre,ctprecor[l][m][ipre],deltaqpre * ctprecor[l][m][ipre]);
		    if ( clevel1->estrip[j][m][l] != 0. ) clevel1->estrip[j][m][l] += deltaqpre * ctprecor[l][m][ipre];
		  } else {
		    if ( clevel1->estrip[j][m][l] != 0. ) clevel1->estrip[j][m][l] += deltaqpre * 0.00478;
		  };
 	          if ( clevel1->estrip[j][m][l] > 0. ) nqpre += clevel1->estrip[j][m][l] ; 
		};
		if ( ctground ) it = 100;
                it++;
		deltaqpre = nqpre - qpre[l][m][ipre];
                if ( debug ) printf(" CK1 BEFORE: qpre %f \n",qpre[l][m][ipre]);   
                qpre[l][m][ipre] = nqpre;
                if ( debug ) printf(" CK1 AFTER: qpre %f \n",qpre[l][m][ipre]);  
	      };
	      //
	    };
	    //
	    // No baseline calculation due to high energy release
	    //
	    if (ck[l][m][pre] == 2 && ck[l][m][pre-1] == 2){
	      //
	      // y^
	      //  |
	      //  |    6 7 8 
	      //  |    3 4 5   
	      //  |    0 1 2 
	      //  | --------------------------------------> x 
	      //
	      Int_t si1 = 0;
	      Int_t si2 = 0;
	      Int_t si3 = 0;
	      if ( l == 0 ){
		if ( ladder == 0 ){
		  si1 = 0;
		  si2 = 3;
		  si3 = 6;
		};
		if ( ladder == 1 ){
		  si1 = 1;
		  si2 = 4;
		  si3 = 7;
		};
		if ( ladder == 2 ){
		  si1 = 2;
		  si2 = 5;
		  si3 = 8;
		};
	      } else {
		if ( ladder == 0 ){
		  si1 = 0;
		  si2 = 1;
		  si3 = 2;
		};
		if ( ladder == 1 ){
		  si1 = 3;
		  si2 = 4;
		  si3 = 5;
		};
		if ( ladder == 2 ){
		  si1 = 6;
		  si2 = 7;
		  si3 = 8;
		};
	      };
	      //
	      // Find the energy distribution along the considered plane looking at the two sandwiching plane of the other view.
	      //
	      Float_t sied[3] = {0.,0.,0.};
	      Int_t othv = !l;
	      Int_t othpl1 = m - 1;
	      Int_t othpl2 = m + 1;
	      Float_t oprof[3] = {0.,0.,0.};
	      for(Int_t s=0; s<3; s++){
		for(Int_t t=(s*32); t<32*(s + 1); t++){	      
		  if ( othpl1 > -1 ) {
		    oprof[s] += clevel1->estrip[othv][othpl1][t];
		  };
		  if ( othpl2 < 22 ) {
		    oprof[s] += clevel1->estrip[othv][othpl2][t];
		  };	      
		};
	      };
	      Float_t otote = fabs(oprof[0]) + fabs(oprof[1]) + fabs(oprof[2]);
	      for(Int_t g=0; g<3; g++){
		if ( otote > 0. ){
		  sied[g] = fabs(oprof[g])/otote;
		} else {
		  sied[g] = 1./3.;
		};
	      };
	      //
	      //
	      //
	      Int_t it = 0;
	      Int_t jpre = 0;
	      Float_t nqsi = 0.;
	      Float_t snqsi = qsi[ladder];
	      Float_t nqpre[2] = {0.,0.};
	      Float_t deltaqsi = qsi[ladder];
	      Float_t deltaqpre[2];
	      deltaqpre[0] = qpre[l][m][pre-1];
	      deltaqpre[1] = qpre[l][m][pre];
              //
              if ( debug ) printf(" Limit for while: 0.07 it < 10 \n");
	      //
	      // these values are empirically determined, usually the routine converge due to deltaqsi and the latest applied correction is based on less than 1 mip
	      //
	      while ( it < 10 && (deltaqsi > 0.07 || deltaqpre[0] > 0.07 || deltaqpre[1] > 0.07) ){
		nqsi = 0.;
		nqpre[0] = 0.;
		nqpre[1] = 0.;
 	        for (Int_t j = ladder*32 ; j < (ladder+1)*32 ; j++){
                  ipre = 0;
		  if ( j > (ladder*32)+15 ) ipre = 1;
                  jpre = j/16 ;
		  //
		  // Silicon effect on the baseline when using the same pre previous baseline (ck = 2) + pre-amply effect
		  //	      
		  if ( !ctground ){
		    if ( debug ) printf(" silicon correction: iteration %i deltaqsi[%i] %f ctsicor %f %f %f sied %f %f %f si %i %i %i TOTAL CORRECTION %f \n",it,ladder,deltaqsi,ctsicor[l][m][si1],ctsicor[l][m][si2],ctsicor[l][m][si3],sied[0],sied[1],sied[2],si1,si2,si3,deltaqsi * (ctsicor[l][m][si1] * sied[0] + ctsicor[l][m][si2] * sied[1] + ctsicor[l][m][si3] * sied[2]));
		    if ( debug ) printf(" pre correction: iteration %i deltaqpre[0] %f deltaqpre[1] %f ctprecor %f  TOTAL CORRECTION %f \n",it,deltaqpre[0],deltaqpre[1],ctprecor[l][m][jpre],deltaqpre[ipre] * ctprecor[l][m][jpre]);
		    if ( clevel1->estrip[j][m][l] != 0. ) clevel1->estrip[j][m][l] +=  (deltaqsi * (ctsicor[l][m][si1] * sied[0] + ctsicor[l][m][si2] * sied[1] + ctsicor[l][m][si3] * sied[2])/mip[l][m][j]) + deltaqpre[ipre] * ctprecor[l][m][jpre];
		  } else {
		    if ( clevel1->estrip[j][m][l] != 0. ) clevel1->estrip[j][m][l] +=  0. + qpre[l][m][jpre] * 0.00478; // no correction
		  };
 	          if ( clevel1->estrip[j][m][l] > 0. ) nqsi += clevel1->estrip[j][m][l] ;
 	          if ( clevel1->estrip[j][m][l] > 0. ) nqpre[ipre] += clevel1->estrip[j][m][l] ; 
                };	
	        if ( ctground ) it = 100;
		deltaqsi = nqsi-snqsi;
		snqsi = nqsi;
                it++;
		deltaqpre[0] = nqpre[0] - qpre[l][m][pre-1];
		deltaqpre[1] = nqpre[1] - qpre[l][m][pre];
                if ( debug ) printf(" BEFORE: qpre 0 %f qpre 1 %f \n",qpre[l][m][pre-1],qpre[l][m][pre]);   
                qpre[l][m][pre-1] = nqpre[0];
                qpre[l][m][pre] = nqpre[1];	
                if ( debug ) printf(" AFTER: qpre 0 %f qpre 1 %f \n",qpre[l][m][pre-1],qpre[l][m][pre]);   
              };
              //
              //
              //
//	      for (Int_t j = ladder*32 ; j < (ladder+1)*32 ; j++){
//		ipre = j/16 ;		
//		//
//		// pre-amplifier effect on baseline when using the same pre previous event baseline (ck=2) 
//		//
//		if ( !ctground ){
//		  if ( clevel1->estrip[j][m][l] != 0. ) clevel1->estrip[j][m][l] +=  qpre[l][m][ipre] * ctprecor[l][m][ipre];
//		} else {
//		  if ( clevel1->estrip[j][m][l] != 0. ) clevel1->estrip[j][m][l] +=  qpre[l][m][ipre] * 0.00478;
//		};
//	      };
	    };
	  };
	};
      };
      //
      Int_t j4 = -4;
      Int_t jjj = -3;
      Int_t jj = -2;
      Int_t jjpre = -1;
      Int_t jjjpre = -1;
      memset(ene, 0, 96*sizeof(Float_t));
      for (Int_t j = 0 ; j < 100 ; j++){	  
	jj++;
	jjj++;
	j4++;
	if ( j < 96 ) ene[j] = clevel1->estrip[j][m][l];
	if ( crosst ){
	  //
	  // "Real" crosstalk effect on the neighbour strips respect to the one which have seen the energy deposit
	  //
	  if ( jj >= 0 && jj < 96 ){
	    if ( !ctground ){
	      if ( jj%16 == 0 ) jjpre++; 	      
	      if ( jj != 0 && jj != 32 && jj != 64 && ene[jj-1] != 0. ) ene[jj-1] += -clevel1->estrip[jj][m][l] * ctneigcor[l][m][jjpre];
	      if ( jj != 31 && jj != 63 && jj != 95 && ene[jj+1] != 0. ) ene[jj+1] += -clevel1->estrip[jj][m][l] * ctneigcor[l][m][jjpre];			
	    } else {
	      if ( jj != 0 && jj != 32 && jj != 64 && ene[jj-1] != 0. ) ene[jj-1] += -clevel1->estrip[jj][m][l] * 0.01581;
	      if ( jj != 31 && jj != 63 && jj != 95 && ene[jj+1] != 0. ) ene[jj+1] += -clevel1->estrip[jj][m][l] * 0.01581;			
	    };
	  };
	  if ( jjj >= 0 && jjj < 96 ){
	    if ( !ctground ){
	      if ( jjj%16 == 0 ) jjjpre++; 	      
	      if ( jjj != 0 && jjj != 32 && jjj != 64 && clevel1->estrip[jjj-1][m][l] != 0. ) clevel1->estrip[jjj-1][m][l] +=  -ene[jjj] * ctneigcor[l][m][jjjpre];
	      if ( jjj != 31 && jjj != 63 && jjj != 95 && clevel1->estrip[jjj+1][m][l] !=0. ) clevel1->estrip[jjj+1][m][l] +=  -ene[jjj] * ctneigcor[l][m][jjjpre];
	    } else {
	      if ( jjj != 0 && jjj != 32 && jjj != 64 && clevel1->estrip[jjj-1][m][l] != 0. ) clevel1->estrip[jjj-1][m][l] +=  -ene[jjj] * 0.01581;
	      if ( jjj != 31 && jjj != 63 && jjj != 95 && clevel1->estrip[jjj+1][m][l] != 0. ) clevel1->estrip[jjj+1][m][l] +=  -ene[jjj] * 0.01581;
	    };
	  };
	};
	if ( j4 >= 0 && j4 < 96 ){
	  //
	  // CALOLEVEL1 CODING AND FILLING
	  //
	  //
	  // NOTICE: THE FOLLOWING LINE EXCLUDE ALL STRIPS FOR WHICH THE RMS*4 IS GREATER THAN 26 !!! <=============== IMPORTANT! =================> // not true anymore, now it trust parameter files
	  //
	  if ( obadmask[l][m][j4] == 1 || clevel1->estrip[j4][m][l] <= clevel1->emin || clevel1->estrip[j4][m][l] <= memin[l][m][j4] || calrms[l][m][j4] > maxrms[l][m] || (l==0 && m == 18 && mask18 ) ){
	    clevel1->estrip[j4][m][l] = 0.;
	  };
	  //
	  if ( debug ) printf(" STRIP: view %i plane %i strip %i energy: %f \n",l,m,j4,clevel1->estrip[j4][m][l]);
	  //
	  // code and save the energy for each strip in svstrip	    
	  //
	  if ( clevel1->estrip[j4][m][l] > clevel1->emin ){
	    //
	    Float_t savel1 = clevel1->estrip[j4][m][l];
	    //
	    if ( m == 18 && l == 0 ){
	      if ( debug ) printf(" Resetting plane 18X for variable calculation: view %i plane %i strip %i \n",l,m,j4);
	      clevel1->estrip[j4][m][l] = 0.; // SAVE STRIPS VALUE FOR PLANE 18 X but DO NOT USE IT FOR VARIABLE CALCULATION
	    };
	    if ( debug ) printf(" HIT STRIP: view %i plane %i strip %i energy: %f \n",l,m,j4,clevel1->estrip[j4][m][l]);
	    //	    if ( dexyc[l][m][j4] == 32767. ){
	    if ( dexyc[l][m][j4] > 32000. ){
	      savel1 += 5000.; 
	      clevel2->nsatstrip += 1.;
	    };
	    //
	    tim = 100000.;
	    plo = m;
	    fbi = 0;
	    if ( savel1 > 0.99995 ){
	      tim = 10000.;
	      plo = m;
	      fbi = 1;
	    };
	    if ( savel1 > 9.9995 ){
	      tim = 1000.;
	      plo = 22 + m;
	      fbi = 1;
	    };
	    if ( savel1 > 99.995 ){
	      tim = 100.;
	      plo = 22 + m;
	      fbi = 0;
	    };
	    if ( savel1 > 999.95 ){
	      tim = 10.;
	      plo = 44 + m;
	      fbi = 0;
	    };
	    if ( savel1 > 9999.5 ){
	      tim = 1.;
	      plo = 66 + m;
	      fbi = 0;
	    };
	    //
	    cle = (Int_t)lroundf(tim*savel1); 
	    //
	    if ( l == 0 ){
	      //
	      // +-PPSSmmmm.mmmm
	      //
	      svstrip[istrip] = fbi*1000000000 + plo*10000000 + j4*100000 + cle;
	    } else {
	      svstrip[istrip] = -(fbi*1000000000 + plo*10000000 + j4*100000 + cle);
	    };
	    //
	    istrip++;
	  };
	};
      };
      //
    };
  };
  //
  // store goodness flag
  //
  if ( !pe  ){
    clevel2->good = 1;
  } else {
    clevel2->good = 0;
  };
  //
  // done
  //
  return(0);
}

void CaloLevel0::GetTrkVar(){
  calol2tr();
}

void CaloLevel0::FillTrkVar(CaloLevel2 *ca, Int_t nutrk){
  //
  CaloTrkVar *t_ca = new CaloTrkVar();
  //
  t_ca->trkseqno = trkseqno; 
  t_ca->ncore = (Int_t)clevel2->ncore; 
  t_ca->qcore = clevel2->qcore;
  t_ca->noint = (Int_t)clevel2->noint;
  t_ca->ncyl = (Int_t)clevel2->ncyl;
  t_ca->qcyl = clevel2->qcyl;
  t_ca->qtrack = clevel2->qtrack;
  t_ca->qtrackx = clevel2->qtrackx;
  t_ca->qtracky = clevel2->qtracky;
  t_ca->dxtrack = clevel2->dxtrack;
  t_ca->dytrack = clevel2->dytrack;
  t_ca->qlast = clevel2->qlast;
  t_ca->nlast = (Int_t)clevel2->nlast;
  t_ca->qpre = clevel2->qpre;
  t_ca->npre = (Int_t)clevel2->npre;
  t_ca->qpresh = clevel2->qpresh;
  t_ca->npresh = (Int_t)clevel2->npresh;
  t_ca->qtr = clevel2->qtr;
  t_ca->ntr = (Int_t)clevel2->ntr;
  t_ca->planetot = (Int_t)clevel2->planetot;
  t_ca->qmean = clevel2->qmean;
  t_ca->dX0l = clevel2->dX0l;
  t_ca->qlow = clevel2->qlow;
  t_ca->nlow = (Int_t)clevel2->nlow;
  //
  if ( trkseqno == -1 ){
    //    ca->impx = clevel2->impx;
    //    ca->impy = clevel2->impy;
    ca->tanx[1] = clevel2->tanx;
    ca->tany[1] = clevel2->tany;
    ca->elen = clevel2->elen;
    ca->selen = clevel2->selen;
    //    memcpy(ca->cibar,clevel2->cibar,sizeof(clevel2->cibar));
    //    memcpy(ca->cbar,clevel2->cbar,sizeof(clevel2->cbar));
    memcpy(t_ca->tibar,clevel2->cibar,sizeof(clevel2->cibar));
    memcpy(t_ca->tbar,clevel2->cbar,sizeof(clevel2->cbar));
    memcpy(ca->planemax,clevel2->planemax,sizeof(clevel2->planemax));
    memcpy(ca->selfdelay,clevel2->selfdelay,sizeof(clevel2->selfdelay));
    ca->varcfit[2] = clevel2->varcfit[0];
    ca->varcfit[3] = clevel2->varcfit[1];
    ca->npcfit[2] = clevel2->npcfit[0];
    ca->npcfit[3] = clevel2->npcfit[1];    
    //    memcpy(ca->varcfit,clevel2->varcfit,sizeof(clevel2->varcfit));
    //    memcpy(ca->npcfit,clevel2->npcfit,sizeof(clevel2->npcfit));
  } else {
    memcpy(t_ca->tibar,clevel2->tibar,sizeof(clevel2->tibar));
    memcpy(t_ca->tbar,clevel2->tbar,sizeof(clevel2->tbar));
  };
  //
  // 
  if ( !(ca->CaloTrk) ) ca->CaloTrk = new TClonesArray("CaloTrkVar",1); //ELENA
  TClonesArray &t = *ca->CaloTrk;
  new(t[nutrk]) CaloTrkVar(*t_ca);
  //
  delete t_ca;
  //
  ClearTrkVar();
}

void CaloLevel0::GetCommonVar(){
  calol2cm();
}

void CaloLevel0::FillCommonVar(CaloLevel1 *c1, CaloLevel2 *ca){
  //
  ca->good = clevel2->good;
//   if ( clevel2->trigty == 2. ){
//     ca->selftrigger = 1;
//   } else {
//     ca->selftrigger = 0;
//   };
  //
  ca->selftrigger = (Int_t)clevel2->trigty + (Int_t)clevel2->wartrig;
  //
  memcpy(ca->perr,clevel2->perr,sizeof(clevel2->perr));
  memcpy(ca->swerr,clevel2->swerr,sizeof(clevel2->swerr));
  memcpy(ca->crc,clevel2->crc,sizeof(clevel2->crc));
  ca->nstrip = (Int_t)clevel2->nstrip;
  ca->nsatstrip = (Int_t)clevel2->nsatstrip;
  ca->qtot = clevel2->qtot;
  //  ca->impx = clevel2->impx;
  //  ca->impy = clevel2->impy;
  ca->tanx[0] = clevel2->tanx;
  ca->tany[0] = clevel2->tany;
  ca->nx22 = (Int_t)clevel2->nx22;
  ca->qx22 = clevel2->qx22;
  ca->qmax = clevel2->qmax;
  ca->elen = clevel2->elen;
  ca->selen = clevel2->selen;
  memcpy(ca->qq,clevel2->qq,sizeof(clevel2->qq));
  memcpy(ca->planemax,clevel2->planemax,sizeof(clevel2->planemax));
  memcpy(ca->selfdelay,clevel2->selfdelay,sizeof(clevel2->selfdelay));
  ca->varcfit[0] = clevel2->varcfit[0];
  ca->varcfit[1] = clevel2->varcfit[1];
  ca->npcfit[0] = clevel2->npcfit[0];
  ca->npcfit[1] = clevel2->npcfit[1]; 
  ca->fitmode[0] = clevel2->fmode[0];
  ca->fitmode[1] = clevel2->fmode[1];
  //  memcpy(ca->varcfit,clevel2->varcfit,sizeof(clevel2->varcfit));
  //  memcpy(ca->npcfit,clevel2->npcfit,sizeof(clevel2->npcfit));
  memcpy(ca->cibar,clevel2->cibar,sizeof(clevel2->cibar));
  memcpy(ca->cbar,clevel2->cbar,sizeof(clevel2->cbar));
  //
  if ( c1 ){
    c1->istrip = istrip;
    c1->estrip = TArrayI(istrip,svstrip);
  };
  //
}

void CaloLevel0::ClearStructs(){
  ClearTrkVar();
  ClearCommonVar();
}

void CaloLevel0::Delete(Option_t *t){
  if ( de ) delete de;
  delete this;
}


void CaloLevel0::RunClose(){
  l0tr->Delete();
  ClearStructs();
  //
  memset(dexy, 0, 2*22*96*sizeof(Float_t));
  memset(dexyc, 0, 2*22*96*sizeof(Float_t));
  memset(base, 0, 2*22*6*sizeof(Float_t));
  memset(sbase, 0, 2*22*6*sizeof(Float_t));
  memset(ctprecor, 0, 2*22*6*sizeof(Float_t));
  memset(ctsicor, 0, 2*22*9*sizeof(Float_t));
  memset(ctneigcor, 0, 2*22*6*sizeof(Float_t));
  //
}

//
// Private methods
//

void CaloLevel0::ClearTrkVar(){
  clevel2->ncore = 0; 
  clevel2->qcore = 0.;
  clevel2->noint = 0.;
  clevel2->ncyl = 0.;
  clevel2->qcyl = 0.;
  clevel2->qtrack = 0.;
  clevel2->qtrackx = 0.;
  clevel2->qtracky = 0.;
  clevel2->dxtrack = 0.;
  clevel2->dytrack = 0.;
  clevel2->qlast = 0.;
  clevel2->nlast = 0.;
  clevel2->qpre = 0.;
  clevel2->npre = 0.;
  clevel2->qpresh = 0.;
  clevel2->npresh = 0.;
  clevel2->qlow = 0.;
  clevel2->nlow = 0.;
  clevel2->qtr = 0.;
  clevel2->ntr = 0.;
  clevel2->planetot = 0.;
  clevel2->qmean = 0.;
  clevel2->dX0l = 0.;
  clevel2->elen = 0.;
  clevel2->selen = 0.;
  memset(clevel1->al_p, 0, 5*2*sizeof(Double_t));
  memset(clevel2->tibar, 0, 2*22*sizeof(Int_t));
  memset(clevel2->tbar, 0, 2*22*sizeof(Float_t));
}

void CaloLevel0::ClearCommonVar(){
  istrip = 0;
  clevel2->trigty = -1.;
  clevel2->wartrig = 0.;
  clevel2->good = 0;
  clevel2->nstrip = 0.;
  clevel2->nsatstrip = 0.;
  clevel2->qtot = 0.;
  //  clevel2->impx = 0.;
  //  clevel2->impy = 0.;
  clevel2->tanx = 0.; // this is correct since it refers to the fortran structure
  clevel2->tany = 0.; // this is correct since it refers to the fortran structure
  clevel2->qmax = 0.;
  clevel2->nx22 = 0.;
  clevel2->qx22 = 0.;
  memset(clevel2->perr, 0, 4*sizeof(Int_t));
  memset(clevel2->swerr, 0, 4*sizeof(Int_t));
  memset(clevel2->crc, 0, 4*sizeof(Int_t));
  memset(clevel2->qq, 0, 4*sizeof(Int_t));
  memset(clevel2->varcfit, 0, 4*sizeof(Float_t));
  memset(clevel2->npcfit, 0, 4*sizeof(Int_t));
  memset(clevel2->planemax, 0, 2*sizeof(Int_t));
  memset(clevel2->selfdelay, 0, 4*7*sizeof(Int_t));
  memset(clevel2->fmode, 0, 2*sizeof(Int_t));
  memset(clevel2->cibar, 0, 2*22*sizeof(Int_t));
  memset(clevel2->cbar, 0, 2*22*sizeof(Float_t));
}

void CaloLevel0::ClearCalibVals(Int_t s){
  //
  for ( Int_t d=0 ; d<11 ;d++  ){
    Int_t pre = -1;
    for ( Int_t j=0; j<96 ;j++){
      if ( j%16 == 0 ) pre++;
      if ( s == 2 ){
	calped[0][2*d+1][j] = 0.;
	cstwerr[3] = 0.;
	cperror[3] = 0.;
	calgood[0][2*d+1][j] = 0.;
	calthr[0][2*d+1][pre] = 0.;
	calrms[0][2*d+1][j] = 0.;
	calbase[0][2*d+1][pre] = 0.;
	calvar[0][2*d+1][pre] = 0.;
      };
      if ( s == 3 ){
	calped[0][2*d][j] = 0.;
	cstwerr[1] = 0.;
	cperror[1] = 0.;
	calgood[0][2*d][j] = 0.;
	calthr[0][2*d][pre] = 0.;
	calrms[0][2*d][j] = 0.;
	calbase[0][2*d][pre] = 0.;
	calvar[0][2*d][pre] = 0.;
      };
      if ( s == 0 ){
	calped[1][2*d][j] = 0.;
	cstwerr[0] = 0.;
	cperror[0] = 0.;
	calgood[1][2*d][j] = 0.;
	calthr[1][2*d][pre] = 0.;
	calrms[1][2*d][j] = 0.;
	calbase[1][2*d][pre] = 0.;
	calvar[1][2*d][pre] = 0.;
      };
      if ( s == 1 ){
	calped[1][2*d+1][j] = 0.;
	cstwerr[2] = 0.;
	cperror[2] = 0.;
	calgood[1][2*d+1][j] = 0.;
	calthr[1][2*d+1][pre] = 0.;
	calrms[1][2*d+1][j] = 0.;
	calbase[1][2*d+1][pre] = 0.;
	calvar[1][2*d+1][pre] = 0.;
      };
    };
  };
  return;
}

Int_t CaloLevel0::Update(GL_TABLES *glt, UInt_t atime, Int_t s){
  //
  const TString host = glt->CGetHost();
  const TString user = glt->CGetUser();
  const TString psw = glt->CGetPsw();
  TSQLServer *dbc = TSQLServer::Connect(host.Data(),user.Data(),psw.Data());
  if ( !dbc->IsConnected() ) throw -116;
  stringstream myquery;
  myquery.str("");
  myquery << "SET time_zone='+0:00'";
  dbc->Query(myquery.str().c_str());
  Int_t sgnl = 0;
  //
  GL_CALO_CALIB *glcalo = new GL_CALO_CALIB();
  //
  sgnl = 0;
  //
  idcalib[s] = 0;
  fromtime[s] = 0;
  totime[s] = 0;
  calibno[s] = 0;
  ClearCalibVals(s);
  //
  UInt_t uptime = 0;
  //
  sgnl = glcalo->Query_GL_CALO_CALIB(atime,uptime,s,dbc);
  if ( sgnl < 0 ){
    if ( verbose ) printf(" CALORIMETER - ERROR: error from GLTables\n");
    return(sgnl);
  };
  //  
  idcalib[s] = glcalo->ID_ROOT_L0;
  fromtime[s] = glcalo->FROM_TIME;
  if ( glcalo->TO_TIME < atime ){ // calibration is corrupted and we are using the one that preceed the good one
    totime[s] = uptime;
  } else {
    totime[s] = glcalo->TO_TIME;
  };
  //  totime[s] = glcalo->TO_TIME;
  calibno[s] = glcalo->EV_ROOT;
  //
  if ( totime[s] == 0 ){
    if ( verbose ) printf(" CALORIMETER - WARNING: data with no associated calibration\n");
    ClearCalibVals(s);
    sgnl = 100;      
  };
  //
  // determine path and name and entry of the calibration file
  //
  GL_ROOT *glroot = new GL_ROOT();  
  if ( verbose ) printf("\n");
  if ( verbose ) printf(" ** SECTION %i **\n",s);
  //
  sgnl = glroot->Query_GL_ROOT(idcalib[s],dbc);
  if ( sgnl < 0 ){
    if ( verbose ) printf(" CALORIMETER - ERROR: error from GLTables\n");
    return(sgnl);
  };
  //	
  stringstream name;
  name.str("");
  name << glroot->PATH.Data() << "/";
  name << glroot->NAME.Data();
  //
  fcalname[s] = (TString)name.str().c_str();
  if ( verbose ) printf(" - event at time %u. From time %u to time %u \n   use file %s \n   calibration at entry %i \n\n",atime,fromtime[s],totime[s],fcalname[s].Data(),calibno[s]);
  //
  sgnl = LoadCalib(s);
  //
  if ( sgnl != 0 ) return(sgnl);
  delete glcalo;
  delete glroot;
  //
  return(0);
  //
}

Int_t CaloLevel0::LoadCalib(Int_t s){
  //
  ifstream myfile;
  myfile.open(fcalname[s].Data());
  if ( !myfile ){    
    return(-107);
  };
  myfile.close();
  //
  TFile *File = new TFile(fcalname[s].Data());
  if ( !File ) return(-108);
  TTree *tr = (TTree*)File->Get("CalibCalPed");
  if ( !tr ) return(-109);
  //
  TBranch *calo = tr->GetBranch("CalibCalPed");
  //
  pamela::CalibCalPedEvent *ce = 0;
  tr->SetBranchAddress("CalibCalPed", &ce);
  //
  Long64_t ncalibs = calo->GetEntries();
  //
  if ( !ncalibs ) return(-110); 
  //
  if ( calo->GetEntry(calibno[s]) <= 0 ) throw -36;
  //
  if (ce->cstwerr[s] != 0 && ce->cperror[s] == 0 ) {
    for ( Int_t d=0 ; d<11 ;d++  ){
      Int_t pre = -1;
      for ( Int_t j=0; j<96 ;j++){
	if ( j%16 == 0 ) pre++;
	if ( s == 2 ){
	  calped[0][2*d+1][j] = ce->calped[3][d][j];
	  cstwerr[3] = ce->cstwerr[3];
	  cperror[3] = ce->cperror[3];
	  calgood[0][2*d+1][j] = ce->calgood[3][d][j];
	  calthr[0][2*d+1][pre] = ce->calthr[3][d][pre];
	  calrms[0][2*d+1][j] = ce->calrms[3][d][j];
	  calbase[0][2*d+1][pre] = ce->calbase[3][d][pre];
	  calvar[0][2*d+1][pre] = ce->calvar[3][d][pre];
	};
	if ( s == 3 ){
	  calped[0][2*d][j] = ce->calped[1][d][j];
	  cstwerr[1] = ce->cstwerr[1];
	  cperror[1] = ce->cperror[1];
	  calgood[0][2*d][j] = ce->calgood[1][d][j];
	  calthr[0][2*d][pre] = ce->calthr[1][d][pre];
	  calrms[0][2*d][j] = ce->calrms[1][d][j];
	  calbase[0][2*d][pre] = ce->calbase[1][d][pre];
	  calvar[0][2*d][pre] = ce->calvar[1][d][pre];
	};
	if ( s == 0 ){
	  calped[1][2*d][j] = ce->calped[0][d][j];
	  cstwerr[0] = ce->cstwerr[0];
	  cperror[0] = ce->cperror[0];
	  calgood[1][2*d][j] = ce->calgood[0][d][j];
	  calthr[1][2*d][pre] = ce->calthr[0][d][pre];
	  calrms[1][2*d][j] = ce->calrms[0][d][j];
	  calbase[1][2*d][pre] = ce->calbase[0][d][pre];
	  calvar[1][2*d][pre] = ce->calvar[0][d][pre];
	};
	if ( s == 1 ){
	  calped[1][2*d+1][j] = ce->calped[2][d][j];
	  cstwerr[2] = ce->cstwerr[2];
	  cperror[2] = ce->cperror[2];
	  calgood[1][2*d+1][j] = ce->calgood[2][d][j];
	  calthr[1][2*d+1][pre] = ce->calthr[2][d][pre];
	  calrms[1][2*d+1][j] = ce->calrms[2][d][j];
	  calbase[1][2*d+1][pre] = ce->calbase[2][d][pre];
	  calvar[1][2*d+1][pre] = ce->calvar[2][d][pre];
	};
      };
    };
  } else {
    if ( verbose ) printf(" CALORIMETER - ERROR: problems finding a good calibration in this file! \n\n ");
    return(-111);
  };
  File->Close();
  return(0);
}