// // C/C++ headers //
#include <fstream>
#include <string.h>
#include <iomanip>
//
// ROOT headers
//
#include <TTree.h>
#include <TClassEdit.h>
#include <TObject.h>
#include <TList.h>
#include <TArrayI.h>
#include <TSystem.h>
#include <TSystemDirectory.h>
#include <TString.h>
#include <TFile.h>
#include <TClass.h>
#include <TCanvas.h>
#include <TH1.h>
#include <TH1F.h>
#include <TH2D.h>
#include <TLatex.h>
#include <TPad.h>
#include <TSQLServer.h>
#include <TSQLRow.h>
#include <TSQLResult.h>
#include <TClonesArray.h>
//
// RunInfo header
//
#include <RunInfo.h>
//
// YODA headers
//
#include <PamelaRun.h>
//#include <physics/trigger/TriggerEvent.h>
#include <physics/tof/TofEvent.h>
//
// This program headers
//
#include <ToFCore.h>
#include <ToFLevel2.h>
#include <ToFVerl2.h>
//
//
// Declaration of the core fortran routines
//
#define tofl2com tofl2com_
extern "C" int tofl2com();
#define toftrk toftrk_
extern "C" int toftrk();
#define rdtofcal rdtofcal_
//extern "C" int rdtofcal(char [], int *);
extern "C" int rdtofcal(const char *, int *);

//
// Tracker classes headers and definitions
//
#include <TrkLevel2.h>
#include <ExtTrack.h> // new tracking code 
//
using namespace std;
//
//
// CORE ROUTINE
//
//
int ToFCore(UInt_t run, TFile *file, GL_TABLES *glt, Int_t ToFargc, char *ToFargv[]){
  //
  //
  // Set these to true to have a very verbose output.
  //
  Bool_t verbose = false;
  Bool_t debug = false;
  //
  Bool_t l1only = false;
  //
  Bool_t deltree = false;
  //
  //
  TString processFolder = Form("ToFFolder_%u",run);
  if ( ToFargc > 0 ){
    Int_t i = 0;
    while ( i < ToFargc ){
      if ( !strcmp(ToFargv[i],"-processFolder") ) {
	if ( ToFargc < i+1 ){
	  throw -3;
	};
	processFolder = (TString)ToFargv[i+1];
	i++;
      };
      if ( !strcmp(ToFargv[i],"-v") ||  !strcmp(ToFargv[i],"--verbose") ) {
	verbose = true;
      };
      if ( !strcmp(ToFargv[i],"-g") ||  !strcmp(ToFargv[i],"--debug") ) {
	verbose = true;
	debug = true;
      };
      if ( !strcmp(ToFargv[i],"--level1-only")  ) {
	l1only = true;
      }
      if ( !strcmp(ToFargv[i],"--delete-tree")  ) {
	deltree = true;
      }
      i++;
    };
  };
  //
  //
  // Output directory is the working directoy.
  //
  const char* outdir = gSystem->DirName(gSystem->DirName(file->GetPath()));
  //
  // Variables for level2 
  //
  TTree *tracker = 0;
  TTree *trigger = 0;
  TTree *toft = 0;
  UInt_t nevents = 0;
  Long64_t maxsize = 10000000000LL;    	 
  TTree::SetMaxTreeSize(maxsize);
  //
  // variables needed to reprocess data
  //
  TString tofversion;
  ItoRunInfo *runinfo = 0;
  TArrayI *runlist = 0;
  TTree *toftclone = 0;
  Bool_t reproc = false;
  Bool_t reprocall = false;
  UInt_t nobefrun = 0;
  UInt_t noaftrun = 0;
  UInt_t numbofrun = 0;
  stringstream ftmpname;
  TString fname;
  UInt_t totfileentries = 0;
  UInt_t idRun = 0;
  //
  // variables needed to handle error signals
  //
  Int_t code = 0;
  Int_t sgnl;
  //
  // tof level2 classes
  //
  ToFLevel2 *tof = new ToFLevel2();
  ToFLevel2 *tofclone = new ToFLevel2();
  ToFdEdx *tofdedx = new ToFdEdx();
  //
  // tracker level2 variables
  //
  TrkLevel2 *trk = new TrkLevel2();
  Int_t nevtrkl2 = 0;
  //
  // trigger level2 variables
  //
  TrigLevel2 *trg = new TrigLevel2();
  Int_t nevtrgl2 = 0;
  //
  // define variables for opening and reading level0 file
  //
  TFile *l0File = 0;
  TTree *l0tr = 0;
  TBranch *l0head = 0;
  //  TBranch *l0trig = 0;
  TBranch *l0tof = 0;
  pamela::EventHeader *eh = 0;
  pamela::PscuHeader *ph = 0;
  //  pamela::trigger::TriggerEvent *trig = 0;
  pamela::tof::TofEvent *tofEvent = 0;
  //
  // Define other basic variables
  // 
  UInt_t procev = 0;
  stringstream file2;
  stringstream file3;
  stringstream qy;
  Int_t itr = -1;    
  Int_t totevent = 0;
  UInt_t atime = 0;
  UInt_t re = 0;
  UInt_t jumped = 0;
  //
  // Working filename
  //
  TString outputfile;
  stringstream name;
  name.str("");
  name << outdir << "/";
  //
  // temporary file and folder
  //
  TFile *tempfile = 0;
  TTree *temptof = 0;
  stringstream tempname;
  stringstream toffolder;
  Bool_t myfold = false;
  tempname.str("");
  tempname << outdir;
  tempname << "/" << processFolder.Data();
  toffolder.str("");
  toffolder << tempname.str().c_str();
  tempname << "/toftree_run";
  tempname << run << ".root";  
  UInt_t totnorun = 0;
  //
  // variables needed to load magnetic field maps
  // 
  Int_t ntrkentry = 0;
  Int_t npmtentry = 0;
  UInt_t tttrkpar1 = 0;
  Bool_t trkpar1 = true;
  UInt_t tttofpar1 = 0;
  Bool_t tofpar1 = true;
  //
  // DB classes
  //
  GL_ROOT *glroot = new GL_ROOT();
  GL_PARAM *glparam = new GL_PARAM();
  GL_TIMESYNC *dbtime = 0;
  //
  // declaring external output and input structures
  //
  extern struct ToFInput  tofinput_;
  extern struct ToFOutput tofoutput_;
  //
  // WM variables perform dE/dx II order corrections
  //
  //Float_t dedx_corr_m[100][48],dedx_corr[48];
  Double_t mtime[100],t1,t2,tm;
  //Float_t yhelp1,yhelp2,slope,inter,thelp1,thelp2;

  //RC variables for new dEdx II order correction (10th reduction)
  Float_t Heyhelp1,Heyhelp2,Heslope,Heinter,thelp1,thelp2;
  Float_t pyhelp1,pyhelp2,pslope,pinter;
  Float_t dedx_Hepeak[48],dedx_ppeak[48];
  Float_t dedx_Hepeak_m[100][48],dedx_ppeak_m[100][48];
  Float_t inter_dedx[48],slope_dedx[48];

  Float_t xmean1,xwidth1;
  Int_t ical,ii,wj,jj;
  Float_t xleft=0;
  Float_t xright=0;
  Float_t yleft=0;
  Float_t yright=0;
  
  Int_t warning = 0;
  int a=0, b=0;

  //
  // Let's start!
  //
  //
  // As a first thing we must check what we have to do: if run = 0 we must process all events in the file has been passed
  // if run != 0 we must process only that run but first we have to check if the tree ToF already exist in the file
  // if it exists we are reprocessing data and we must delete that entries, if not we must create it.
  // 
  if ( run == 0 )  reproc = true;
  //
  //
  // Output file is "outputfile"
  //
  if ( !file->IsOpen() ){
    if ( verbose ) printf(" ToF - ERROR: cannot open file for writing\n");
    throw -301;    
  }

  if ( debug ) file->ls();

  //
  // Delete tree if requested
  //
  if ( deltree ){
    TTree *T = (TTree*)file->Get("ToF");
    if ( T ){
      if ( verbose ) printf(" ToF - REMOVING ToF TTree \n");
      T->Delete("all");
    }
  }
  
  //
  // Does it contain the Tracker tree?
  //
  //
  TClonesArray *tcNucleiTrk = NULL;
  TClonesArray *tcExtNucleiTrk = NULL;
  TClonesArray *tcExtTrk = NULL;
  TClonesArray *ttofNucleiTrk = NULL;
  TClonesArray *ttofExtNucleiTrk = NULL;
  TClonesArray *ttofExtTrk = NULL;
  Bool_t hasNucleiTrk = false;
  Bool_t hasExtNucleiTrk = false;
  Bool_t hasExtTrk = false;
  if ( !l1only ){
    tracker = (TTree*)file->Get("Tracker");
    if ( !tracker ) {
      if ( verbose ) printf(" TOF - ERROR: no tracker tree\n");
      code = -302;
      goto closeandexit;
    }
    //
    // get tracker level2 data pointer
    //
    //    tracker->SetMaxVirtualSize(2500000000LL); // EM residual Tracker-new tree in level2 files when NEVENTS is big
    tracker->SetBranchAddress("TrkLevel2",&trk);  
    nevtrkl2 = tracker->GetEntries();
    //
    // Look for extended tracking algorithm
    //
    if ( verbose ) printf("Look for extended and nuclei tracking algorithms\n"); 
    // Nuclei tracking algorithm
    Int_t checkAlgo = 0;
    tcNucleiTrk =  new TClonesArray("TrkTrack");
    checkAlgo = tracker->SetBranchAddress("TrackNuclei",&tcNucleiTrk);    
    if ( !checkAlgo ){
      if ( verbose ) printf(" Nuclei tracking algorithm branch found! :D \n");
      hasNucleiTrk = true;
    } else {
      if ( verbose ) printf(" Nuclei tracking algorithm branch not found :( !\n");
      printf(" ok, this is not a problem (it depends on tracker settings) \n");
      delete tcNucleiTrk;
      tcNucleiTrk = NULL; // 10RED reprocessing bug when missing extratracks 
    }
    // Nuclei tracking algorithm using calorimeter points
    tcExtNucleiTrk =  new TClonesArray("ExtTrack");
    checkAlgo = tracker->SetBranchAddress("RecoveredTrackNuclei",&tcExtNucleiTrk);    
    if ( !checkAlgo ){
      if ( verbose ) printf(" Recovered nuclei tracking algorithm branch found! :D \n");
      hasExtNucleiTrk = true;
    } else {
      if ( verbose ) printf(" Recovered nuclei tracking algorithm branch not found :( !\n");
      printf(" ok, this is not a problem (it depends on tracker settings) \n");
      delete tcExtNucleiTrk;
      tcExtNucleiTrk = NULL; // 10RED reprocessing bug when missing extratracks 
    }
    // Tracking algorithm using calorimeter points
    tcExtTrk =  new TClonesArray("ExtTrack");
    checkAlgo = tracker->SetBranchAddress("RecoveredTrack",&tcExtTrk);
    if ( !checkAlgo ){
      if ( verbose ) printf(" Recovered track algorithm branch found! :D \n");
      hasExtTrk = true;
    } else {
      if ( verbose ) printf(" Recovered track algorithm branch not found :( !\n");
      printf(" ok, this is not a problem (it depends on tracker settings) \n");
      delete tcExtTrk;
      tcExtTrk = NULL; // 10RED reprocessing bug when missing extratracks 
    }
  }
  //
  // Does it contain the Trigger tree?
  //
  trigger = (TTree*)file->Get("Trigger");
  if ( !trigger ) {
    if ( verbose ) printf(" TOF - ERROR: no trigger tree\n");
    code = -302;
    goto closeandexit;
  };
  //
  // get trigger level2 data pointer
  //
  //  trigger->SetMaxVirtualSize(2500000000LL); // EM residual Tracker-new tree in level2 files when NEVENTS is big
  trigger->SetBranchAddress("TrigLevel2",&trg);  
  nevtrgl2 = trigger->GetEntries();

  //
  // Retrieve GL_RUN variables from the level2 file
  //  
  tofversion = ToFInfo(false); // we should decide how to handle versioning system
  //
  // create an interface to RunInfo called "runinfo"
  //
  // ItoRunInfo= interface with RunInfo and GL_RUN
  runinfo = new ItoRunInfo(file);
  //
  // open "Run" tree in level2 file, if not existing return an error (sngl != 0)
  //
  sgnl = 0;
  sgnl = runinfo->Update(run, "TOF",tofversion);
  if ( sgnl ){
    if ( verbose ) printf(" TOF - ERROR: RunInfo exited with non-zero status\n");
    code = sgnl;
    goto closeandexit;
  } else {
    sgnl = 0;
  };
  //
  // number of events in the file BEFORE the first event of our run
  //
  nobefrun = runinfo->GetFirstEntry();
  //
  // total number of events in the file 
  //
  totfileentries = runinfo->GetFileEntries();
  //
  // first file entry AFTER the last event of our run
  //
  noaftrun = runinfo->GetLastEntry() + 1;
  //
  // number of run to be processed
  //
  numbofrun = runinfo->GetNoRun();
  totnorun = runinfo->GetRunEntries();
  //
  // Try to access the ToF tree in the file, if it exists we are reprocessing data if not we are processing a new run
  //
  toftclone = (TTree*)file->Get("ToF");
  //
  if ( !toftclone ){
    //
    // tree does not exist, we are not reprocessing
    //
    reproc = false;
    if ( run == 0 && verbose ) printf(" ToF - WARNING: you are reprocessing data but ToF tree does not exist!\n");
    if ( runinfo->IsReprocessing() && run != 0 && verbose ) printf(" ToF - WARNING: it seems you are not reprocessing data but ToF\n versioning information already exists in RunInfo.\n");

  } else {
    //
    // tree exists, we are reprocessing data. Are we reprocessing a single run or all the file?
    //
    //    toftclone->SetMaxVirtualSize(2500000000LL); // EM residual Tracker-new tree in level2 files when NEVENTS is big
    toftclone->SetAutoSave(900000000000000LL);
    reproc = true;
    //
    // update versioning information
    //
    if ( verbose ) printf("\n Preparing the pre-processing...\n");
    //
    if ( run == 0 || totnorun == 1 ){
      //
      // we are reprocessing all the file
      // if we are reprocessing everything we don't need to copy any old event and we can just work with the new tree and delete the old one immediately
      //
      reprocall = true;
      //
      if ( verbose ) printf("\n ToF - WARNING: Reprocessing all runs\n");
      //
    } else {
      //
      // we are reprocessing a single run, we must copy to the new tree the events in the file which preceed the first event of the run
      //
      reprocall = false;
      //
      if ( verbose ) printf("\n ToF - WARNING: Reprocessing run number %u \n",run);
      //
      // copying old tree to a new file
      //
      gSystem->MakeDirectory(toffolder.str().c_str());
      myfold = true;
      tempfile = new TFile(tempname.str().c_str(),"RECREATE");
      temptof = toftclone->CloneTree(-1,"fast");
      temptof->SetName("ToF-old");
      tempfile->Write();
      tempfile->Close();  
    }
    //
    // Delete the old tree from old file and memory
    //
    toftclone->Delete("all");
    //
    if ( verbose ) printf(" ...done!\n");
    //
  };
  //
  // create ToF detector tree toft
  // 
  file->cd();
  toft = new TTree("ToF-new","PAMELA Level2 ToF data");
  //  toft->SetMaxVirtualSize(2500000000LL); // EM residual Tracker-new tree in level2 files when NEVENTS is big
  toft->SetAutoSave(900000000000000LL);  	 
  tof->Set();//ELENA **TEMPORANEO?**
  toft->Branch("ToFLevel2","ToFLevel2",&tof);
  //
  // create new branches for new tracking algorithms
  //
  if ( hasNucleiTrk ){
    ttofNucleiTrk = new TClonesArray("ToFTrkVar",1);
    toft->Branch("TrackNuclei",&ttofNucleiTrk);
  }
  if ( hasExtNucleiTrk ){
    ttofExtNucleiTrk = new TClonesArray("ToFTrkVar",1);
    toft->Branch("RecoveredTrackNuclei",&ttofExtNucleiTrk);
  }
  if ( hasExtTrk ){
    ttofExtTrk = new TClonesArray("ToFTrkVar",1);
    toft->Branch("RecoveredTrack",&ttofExtTrk);
  }

  //
  if ( reproc && !reprocall ){
    //
    //  open new file and retrieve all tree informations
    //
    tempfile = new TFile(tempname.str().c_str(),"READ");
    toftclone = (TTree*)tempfile->Get("ToF-old");
    //    toftclone->SetMaxVirtualSize(2500000000LL); // EM residual Tracker-new tree in level2 files when NEVENTS is big
    toftclone->SetAutoSave(900000000000000LL);
    toftclone->SetBranchAddress("ToFLevel2",&tofclone); // EM reprocessing bug fixed 
    //      
    if ( nobefrun > 0 ){
      if ( verbose ) printf("\n Pre-processing: copying events from the old tree before the processed run\n");   
      if ( verbose ) printf(" Copying %u events in the file which are before the beginning of the run %u \n",nobefrun,run);
      if ( verbose ) printf(" Start copying at event number 0, end copying at event number %u \n",nobefrun);
      for (UInt_t j = 0; j < nobefrun; j++){
	//
	if ( toftclone->GetEntry(j) <= 0 ) throw -36;	  
	//
	// copy tofclone to tof
	//
	memcpy(&tof,&tofclone,sizeof(tofclone));
	//
	// Fill entry in the new tree
	//
	toft->Fill();
	//
      }
      if ( verbose ) printf(" Finished successful copying!\n");
    }         
  }
  //
  // Get the list of run to be processed, if only one run has to be processed the list will contain one entry only.
  //
  runlist = runinfo->GetRunList();
  //
  // Loop over the run to be processed
  //
  for (UInt_t irun=0; irun < numbofrun; irun++){
    //
    // retrieve the first run ID to be processed using the RunInfo list
    //
    idRun = runlist->At(irun);
    if ( verbose ) printf("\n\n\n ####################################################################### \n");
    if ( verbose ) printf("                    PROCESSING RUN NUMBER %u \n",idRun);
    if ( verbose ) printf(" ####################################################################### \n\n\n");
    //
    runinfo->ID_ROOT_L0 = 0;
    //
    // store in the runinfo class the GL_RUN variables for our run
    //
    sgnl = 0;
    sgnl = runinfo->GetRunInfo(idRun);
    if ( sgnl ){
      if ( verbose ) printf(" TOF - ERROR: RunInfo exited with non-zero status\n");
      code = sgnl;
      goto closeandexit;
    } else {
      sgnl = 0;
    };
    //
    // now you can access that variables using the RunInfo class this way runinfo->ID_ROOT_L0
    //
    if ( runinfo->ID_ROOT_L0 == 0 ){
      if ( verbose ) printf("\n TOF - ERROR: no run with ID_RUN = %u \n\n Exiting... \n\n",idRun);
      code = -5;
      goto closeandexit;    
    };
    //
    // prepare the timesync for the db
    //
    TString host = glt->CGetHost();
    TString user = glt->CGetUser();
    TString psw = glt->CGetPsw();
    TSQLServer *dbc = TSQLServer::Connect(host.Data(),user.Data(),psw.Data());
    if ( !dbc->IsConnected() ) throw -314;
    stringstream myquery;
    myquery.str("");
    myquery << "SET time_zone='+0:00';";
    delete dbc->Query(myquery.str().c_str());
    delete dbc->Query("SET sql_mode = 'NO_UNSIGNED_SUBTRACTION';");
    dbtime = new GL_TIMESYNC(runinfo->ID_ROOT_L0,"ID",dbc);
    //
    // Search in the DB the path and name of the LEVEL0 file to be processed.
    //
    //    if ( !dbc->IsConnected() ) throw -314;
    glroot->Query_GL_ROOT(runinfo->ID_ROOT_L0,dbc);
    //
    ftmpname.str("");
    ftmpname << glroot->PATH.Data() << "/";
    ftmpname << glroot->NAME.Data();
    fname = ftmpname.str().c_str();
    //
    // print out informations
    //
    totevent = runinfo->NEVENTS;
    if ( verbose ) printf("\n LEVEL0 data file: %s \n",fname.Data());
    if ( verbose ) printf(" RUN HEADER absolute time is:  %u \n",runinfo->RUNHEADER_TIME);
    if ( verbose ) printf(" RUN TRAILER absolute time is: %u \n",runinfo->RUNTRAILER_TIME);
    if ( verbose ) printf(" %i events to be processed for run %u: from %i to %i \n\n",totevent,idRun,runinfo->EV_FROM,runinfo->EV_FROM+totevent);
    //
    //    if ( !totevent ) goto closeandexit;
    //
    // Open Level0 file
    //
    if ( l0File ) l0File->Close();
    l0File = new TFile(fname.Data());
    if ( !l0File ) {
      if ( verbose ) printf(" TOF - ERROR: problems opening  Level0 file\n");
      code = -6;
      goto closeandexit;
    };
    l0tr = (TTree*)l0File->Get("Physics");
    if ( !l0tr ) {
      if ( verbose ) printf(" TOF - ERROR: no Physics tree in Level0 file\n");
      l0File->Close();
      code = -7;
      goto closeandexit;
    };
    l0head = l0tr->GetBranch("Header");
    if ( !l0head ) {
      if ( verbose ) printf(" TOF - ERROR: no Header branch in Level0 tree\n");
      l0File->Close();
      code = -8;
      goto closeandexit;    
    };
    //     l0trig = l0tr->GetBranch("Trigger");
    //     if ( !l0trig ) {
    //       if ( verbose ) printf(" TOF - ERROR: no Trigger branch in Level0 tree\n");
    //       l0File->Close();
    //       code = -300;
    //       goto closeandexit;
    //     };
    l0tof = l0tr->GetBranch("Tof");
    if ( !l0tof ) {
      if ( verbose ) printf(" TOF - ERROR: no ToF branch in Level0 tree\n");
      l0File->Close();
      code = -303;
      goto closeandexit;
    };
    //
    //    l0tr->SetBranchAddress("Trigger", &trig);
    l0tr->SetBranchAddress("Tof", &tofEvent);
    l0tr->SetBranchAddress("Header", &eh);
    //
    nevents = l0tof->GetEntries();
    //
    if ( nevents < 1 && totevent ) {
      if ( verbose ) printf(" TOF - ERROR: Level0 file is empty\n\n");
      l0File->Close();
      code = -11;
      goto closeandexit;
    };
    //
    if ( runinfo->EV_TO > nevents-1 && totevent ) {
      if ( verbose ) printf(" TOF - ERROR: too few entries in the registry tree\n");
      l0File->Close();
      code = -12;
      goto closeandexit;
    };
    //
    // Check if we have to load parameter files (or calibration associated to runs and not to events)
    //
    // for example let's assume that we could have different magnetic field maps for different runs:
    //
    if ( !l1only ){
      if ( trkpar1 || ( tttrkpar1 != 0 && tttrkpar1 < runinfo->RUNHEADER_TIME ) ){
        trkpar1 = false;
        // read from DB infos about Magnetic filed maps
        //      if ( !dbc->IsConnected() ) throw -314;
        glparam->Query_GL_PARAM(runinfo->RUNHEADER_TIME,1,dbc); // parameters stored in DB in GL_PRAM table
        tttrkpar1 = glparam->TO_TIME;  
        // ----------------------------
        // Read the magnetic field
        // ----------------------------
        if ( verbose ) printf(" Reading magnetic field maps: \n");
        trk->LoadField(glparam->PATH+glparam->NAME);
        if ( verbose ) printf("\n");
      }
    }
    //
    // variable to save information about the tof calibration used
    //
    Bool_t defcal = true;
    //
    if ( tofpar1 || ( tttofpar1 != 0 && tttofpar1 < runinfo->RUNHEADER_TIME ) ){
      tofpar1 = false;
      //
      //      if ( !dbc->IsConnected() ) throw -314;
      Int_t error=glparam->Query_GL_PARAM(runinfo->RUNHEADER_TIME,201,dbc); // parameters stored in DB in GL_PRAM table
      if ( error<0 ) {
	code = error;
	goto closeandexit;
      };
      //
      if ( verbose ) printf(" Reading ToF parameter file: %s \n",(glparam->PATH+glparam->NAME).Data());
      //
      if ( (UInt_t)glparam->TO_TIME != (UInt_t)4294967295UL ) defcal = false;
      //
      tttofpar1 = glparam->TO_TIME;  
      Int_t nlen = (Int_t)(glparam->PATH+glparam->NAME).Length();
      //      rdtofcal((char *)(glparam->PATH+glparam->NAME).Data(),&nlen);
      rdtofcal((const char *)(glparam->PATH+glparam->NAME).Data(),&nlen);
      //
    };
    //
    Int_t error=glparam->Query_GL_PARAM(runinfo->RUNHEADER_TIME,204,dbc); // parameters stored in DB in GL_PRAM table
    if ( error<0 ) {
      code = error;
      goto closeandexit;
    };
    //
    if ( verbose ) printf(" Reading ToF attenuation parameter file: %s \n",(glparam->PATH+glparam->NAME).Data());
    tofdedx->ReadParAtt((glparam->PATH+glparam->NAME).Data());

    //
    error=glparam->Query_GL_PARAM(runinfo->RUNHEADER_TIME,205,dbc); // parameters stored in DB in GL_PRAM table
    if ( error<0 ) {
      code = error;
      goto closeandexit;
    };
    //
    if ( verbose ) printf(" Reading ToF desaturation on position parameter file: %s \n",(glparam->PATH+glparam->NAME).Data());
    tofdedx->ReadParPos((glparam->PATH+glparam->NAME).Data());

    //
    error=glparam->Query_GL_PARAM(runinfo->RUNHEADER_TIME,206,dbc); // parameters stored in DB in GL_PRAM table
    if ( error<0 ) {
      code = error;
      goto closeandexit;
    };
    //
    if ( verbose ) printf(" Reading ToF BetheBloch parameter file: %s \n",(glparam->PATH+glparam->NAME).Data());
    tofdedx->ReadParBBneg((glparam->PATH+glparam->NAME).Data());

    //
    error=glparam->Query_GL_PARAM(runinfo->RUNHEADER_TIME,207,dbc); // parameters stored in DB in GL_PRAM table
    if ( error<0 ) {
      code = error;
      goto closeandexit;
    };
    //
    if ( verbose ) printf(" Reading ToF Bethe-Bloch parameter file for beta gt1: %s \n",(glparam->PATH+glparam->NAME).Data());
    tofdedx->ReadParBBpos((glparam->PATH+glparam->NAME).Data());

    //
    error=glparam->Query_GL_PARAM(runinfo->RUNHEADER_TIME,208,dbc); // parameters stored in DB in GL_PRAM table
    if ( error<0 ) {
      code = error;
      goto closeandexit;
    };
    //
    if ( verbose ) printf(" Reading ToF desaturation on beta parameter file: %s \n",(glparam->PATH+glparam->NAME).Data());
    tofdedx->ReadParDesatBB((glparam->PATH+glparam->NAME).Data());


    tofdedx->CheckConnectors(runinfo->RUNHEADER_TIME,glparam,dbc);

    //
    // WM reading parameter file for dE/dx II order corrections
    //
    //memset(dedx_corr_m,0,100*48*sizeof(Float_t));
    //memset(dedx_corr,0,48*sizeof(Float_t));
    //memset(mtime,0,100*sizeof(Double_t));

    //
    // RC reading parameter file for new dE/dx II order correction (10th red)
    //
    memset(dedx_Hepeak_m,0,100*48*sizeof(Float_t));
    memset(dedx_ppeak_m,0,100*48*sizeof(Float_t));
    memset(dedx_Hepeak,0,48*sizeof(Float_t));
    memset(dedx_ppeak,0,48*sizeof(Float_t));
    memset(mtime,0,100*sizeof(Double_t));

    //
    // Query the DB to get the file
    //
    error=glparam->Query_GL_PARAM(runinfo->RUNHEADER_TIME,203,dbc); // parameters stored in DB in GL_PRAM table
    if ( error<0 ) {
      code = error;
      goto closeandexit;
    };
    //
    if ( verbose ) printf(" Reading ToF dE/dx II order correction parameter file: %s \n",(glparam->PATH+glparam->NAME).Data());
    //
    ical=0;  // counter set to zero if first-time reading
    //-----------------------------------------------------------
    // Here I  read the dEdx_korr parameters
    //-----------------------------------------------------------
    jj=0;
    ifstream fin((glparam->PATH+glparam->NAME).Data());
    UInt_t window = 200000;
    Bool_t first = true;
    Bool_t last = true;
    //Float_t sdedx_corr_m[48];
    //memset(sdedx_corr_m,0,48*sizeof(Float_t));

    Float_t sdedx_Hepeak_m[48];
    memset(sdedx_Hepeak_m,0,48*sizeof(Float_t));
    Float_t sdedx_ppeak_m[48];
    memset(sdedx_ppeak_m,0,48*sizeof(Float_t));

    Double_t stm = 0;
    while ( !fin.eof() ){
      stm = tm;
      //      if ( jj > 0 ) memcpy(sdedx_corr_m,dedx_corr_m[jj-1],48*sizeof(Float_t)); // BUG sdedx should be the previous in time not the previous saved [absurd dE/dx for 8th reduction March and > March 2008 data - fixed on 2009/02/04
      fin>>t1>>tm>>t2;
      if ( debug ) cout << setiosflags(ios::fixed)  << setw(10) << setprecision(3) << tm << endl;
      if ( (tm >= (runinfo->RUNHEADER_TIME-window) && tm <= (runinfo->RUNTRAILER_TIME+window)) || (tm > (runinfo->RUNTRAILER_TIME+window) && last) ){
	if ( first ){
	  mtime[jj]=stm;
	  jj++;
	  if ( jj >= 100 ){
	    code = -318;
	    goto closeandexit;
	  };
	};
	mtime[jj]=tm;
      };
      for (ii=0; ii<48;ii++){
	fin>>wj>>xmean1>>xwidth1;
	if ( (tm >= (runinfo->RUNHEADER_TIME-window) && tm <= (runinfo->RUNTRAILER_TIME+window)) || (tm > (runinfo->RUNTRAILER_TIME+window) && last) ){
	  if ( first ){
	    //dedx_corr_m[jj-1][ii]=sdedx_corr_m[ii];

	    dedx_Hepeak_m[jj-1][ii]=sdedx_Hepeak_m[ii];
	    dedx_ppeak_m[jj-1][ii]=sdedx_ppeak_m[ii];
	  };
	  //dedx_corr_m[jj][ii]=xmean1;

	  dedx_Hepeak_m[jj][ii]=xmean1;
	  dedx_ppeak_m[jj][ii]=xwidth1;
	};
	//sdedx_corr_m[ii]=xmean1; // BUG sdedx should be the previous in time not the previous saved [absurd dE/dx for 8th reduction March and > March 2008 data - fixed on 2009/02/04
	sdedx_Hepeak_m[ii]=xmean1;
	sdedx_ppeak_m[ii]=xwidth1;

      };
      if ( (tm >= (runinfo->RUNHEADER_TIME-window) && tm <= (runinfo->RUNTRAILER_TIME+window)) || (tm > (runinfo->RUNTRAILER_TIME+window) && last)){
	if ( first ) first = false;
	if ( tm > (runinfo->RUNTRAILER_TIME+window) ) last = false;
	jj++;
      };
      if ( jj >= 100 ){
	code = -318;
	goto closeandexit;
      };
    };
    //
    fin.close(); 
    // this is a possible bug...
    //    Bool_t ff = false;
    //    while ( runinfo->RUNHEADER_TIME > mtime[ical] && ical < 100 ) {
    //      ical = ical+1;
    //      ff = true;
    //    };
    while ( (mtime[ical] > runinfo->RUNHEADER_TIME || runinfo->RUNHEADER_TIME > mtime[ical+1] ) && ical < 99 ) {
      ical = ical+1;
      //      ff = true;
    };
    //    if ( ff ) ical = ical-1;
    if ( verbose ) cout<<"rh time "<<runinfo->RUNHEADER_TIME<<" rt time "<<runinfo->RUNTRAILER_TIME<<" limit low "<<mtime[ical]<<" limit up "<<mtime[ical+1]<<" ical "<<ical<< " jj " << jj<< endl;
    if ( ical < 0 || ical >= 98 ){
      code = -315;
      goto closeandexit;
    };
    //
    // run over all the events of the run
    //
    if ( verbose ) printf("\n Ready to start! \n\n Processed events: \n\n");
    //
    if ( dbc ){
      dbc->Close();
      delete dbc;
      dbc = 0;
    };
    //
    jumped = 0;
    //
    for ( re = runinfo->EV_FROM; re < (runinfo->EV_FROM+runinfo->NEVENTS); re++){
      //    for ( re = runinfo->EV_FROM; re < (runinfo->EV_FROM+100); re++){ // QUIIIIIII
      //
      if ( procev%1000 == 0 && procev > 0 && verbose ) printf(" %iK \n",procev/1000);	
      //
      if ( l0head->GetEntry(re) <= 0 ) throw -36;
      //
      // absolute time of this event
      //
      ph = eh->GetPscuHeader();
      atime = dbtime->DBabsTime(ph->GetOrbitalTime());  
      //
      tof->Clear();
      Int_t pmt_id = 0;
      ToFPMT *t_pmt = new ToFPMT();
      if(!(tof->PMT))tof->PMT = new TClonesArray("ToFPMT",12); //ELENA
      TClonesArray &tpmt = *tof->PMT;
      ToFTrkVar *t_tof = new ToFTrkVar();
      if(!(tof->ToFTrk))tof->ToFTrk = new TClonesArray("ToFTrkVar",2); //ELENA  	 
      TClonesArray &t = *tof->ToFTrk;
      //
      // paranoid check
      //
      if ( atime > (runinfo->RUNTRAILER_TIME+1) || atime < (runinfo->RUNHEADER_TIME-1)  ) {
	if ( verbose ) printf(" TOF - WARNING: event at time outside the run time window, skipping it\n");
	jumped++;
	goto jumpev;
      };
      //
      // retrieve tracker informations, the LEVEL2 entry which correspond to our event will be "itr"
      //
      if ( !reprocall ){
	itr = nobefrun + (re - runinfo->EV_FROM -jumped);
      } else {
	itr = runinfo->GetFirstEntry() + (re - runinfo->EV_FROM -jumped);
      };
      if ( !l1only ){
        if ( itr > nevtrkl2 ){  // nevtrkl2 tracker entry number
          if ( verbose ) printf(" TOF - ERROR: no tracker events with entry = %i in Level2 file\n",itr);
          l0File->Close();
          code = -313;
          goto closeandexit; 
        }
      }
      if ( itr > nevtrgl2 ){  // nevtrgl2 trigger entry number
	if ( verbose ) printf(" TOF - ERROR: no trigger events with entry = %i in Level2 file\n",itr);
	l0File->Close();
	code = -319;
	goto closeandexit; 
      }
      //
      if ( !l1only ){        
        trk->Clear();
        //
        // Clones array must be cleared before going on
        //
        if ( hasNucleiTrk ){
          tcNucleiTrk->Delete();
          ttofNucleiTrk->Delete();
        }
        if ( hasExtNucleiTrk ){
          tcExtNucleiTrk->Delete();
          ttofExtNucleiTrk->Delete();
        }          
        if ( hasExtTrk ){
          tcExtTrk->Delete();
          ttofExtTrk->Delete();
        }
      }
      trg->Clear();
      //
      if ( !l1only && tracker->GetEntry(itr) <= 0 ) throw -36; 
      if ( trigger->GetEntry(itr) <= 0 ) throw -36; 
      ///
        //
        if ( l0tof->GetEntry(re) <= 0 ) throw -36;
        //      if ( l0trig->GetEntry(re) <= 0 ) throw -36;
        ///
          //
          procev++;
          //
          // start processing
          //
          // dE/dx II order correction: check time limits and interpolate time correction
          //==================================================================
          //==  if time is outside time limits: 
          //==================================================================
          if ( atime<mtime[ical] || atime>mtime[ical+1] ){
            if ( verbose ) cout<<"Checking Time Limits!"<<endl;
            ical=0;
            while ( ( mtime[ical] > atime || atime > mtime[ical+1]) && ical < 99 ){
              ical = ical+1;
            }
            //
            if ( ical < 0 || ical >= 98 ){
              code = -317;
              goto closeandexit;
            };
            if ( verbose ) cout<<"abs time "<<atime<<" limit low "<<mtime[ical]<<" limit up "<<mtime[ical+1]<<" ical "<<ical<<endl;
          };
          //==================================================================
          //== interpolate betwen time limits
          //==================================================================
          thelp1 = mtime[ical];
          thelp2 = mtime[ical+1];
          for (ii=0; ii<48;ii++) {

            Heyhelp1 = fabs(dedx_Hepeak_m[ical][ii]);
            if ( Heyhelp1 < 0.1 ) Heyhelp1 = 4.;
            Heyhelp2 = fabs(dedx_Hepeak_m[ical+1][ii]);
            if ( Heyhelp2 < 0.1 ) Heyhelp2 = 4.;
            Heslope  = (Heyhelp2-Heyhelp1)/(thelp2-thelp1);
            Heinter  = Heyhelp1 - Heslope*thelp1;
            dedx_Hepeak[ii] = Heslope*atime + Heinter;

            pyhelp1 = fabs(dedx_ppeak_m[ical][ii]);
            if ( pyhelp1 < 0.1 ) pyhelp1 = 1.;
            pyhelp2 = fabs(dedx_ppeak_m[ical+1][ii]);
            if ( pyhelp2 < 0.1 ) pyhelp2 = 1.;
            pslope  = (pyhelp2-pyhelp1)/(thelp2-thelp1);
            pinter  = pyhelp1 - pslope*thelp1;
            dedx_ppeak[ii] = pslope*atime + pinter;

            if(dedx_Hepeak[ii]>dedx_ppeak[ii])slope_dedx[ii]=3./(dedx_Hepeak[ii]-dedx_ppeak[ii]);
            else slope_dedx[ii]=4.;
            if(dedx_Hepeak[ii]>dedx_ppeak[ii])inter_dedx[ii]=1.-(slope_dedx[ii]*dedx_ppeak[ii]);
            else inter_dedx[ii]=0.;
            
            if ( fabs(dedx_ppeak[ii]) <= 1e-15 ){
              if ( verbose ) printf("ii %i pslope %f atime %u pinter %f dedx_ppeak %f \n",ii,pslope,atime,pinter,dedx_ppeak[ii]);
              if ( verbose ) printf("ical %i pyhelp2 %f pyhelp1 %f thelp2 %f thelp1 %f \n",ical,pyhelp2,pyhelp1,thelp2,thelp1);
              code = -316;
              goto closeandexit;
            }
          }
          //================================================================
          //================================================================

          //
          // Here we will use some procedure to calibrate our data and put some kind of informations in the cinput structure
          //
          for (Int_t gg=0; gg<4;gg++){
            for (Int_t hh=0; hh<12;hh++){
              tofinput_.tdc[hh][gg] = (0xFFF & tofEvent->tdc[gg][hh]); // exclude warning bits
              tofinput_.adc[hh][gg] = (0xFFF & tofEvent->adc[gg][hh]); // exclude warning bits
            }
          }
          //
          tofdedx->Init(tofEvent);
          warning = 0;
          //
          for (Int_t hh=0; hh<5;hh++){
            tofinput_.patterntrig[hh]=trg->patterntrig[hh];
          }	    
          //
          // Here we have calibrated data, ready to be passed to the FORTRAN routine which will extract common and track-related  variables.
          //
          npmtentry = 0;
          //
          ntrkentry = 0;
          //
          // Calculate tracks informations from ToF alone
          //
          tofl2com();
          //
          memcpy(tof->tof_j_flag,tofoutput_.tof_j_flag,6*sizeof(Int_t));
          //
          if ( !l1only ){
            //
            t_tof->trkseqno = -1;
            //
            // and now we must copy from the output structure to the level2 class:
            //
            t_tof->npmttdc = 0;
            //
            for (Int_t hh=0; hh<12;hh++){
              for (Int_t kk=0; kk<4;kk++){
                if ( tofoutput_.tofmask[hh][kk] != 0 ){
                  pmt_id = tof->GetPMTid(kk,hh);
                  t_tof->pmttdc.AddAt(pmt_id,t_tof->npmttdc);
                  t_tof->tdcflag.AddAt(tofoutput_.tdcflagtof[hh][kk],t_tof->npmttdc); // gf: Jan 09/07
                  t_tof->npmttdc++;
                };
              };
            };
            for (Int_t kk=0; kk<13;kk++){
              t_tof->beta[kk] = tofoutput_.betatof_a[kk];	
            }
            //
            //
            memcpy(t_tof->xtofpos,tofoutput_.xtofpos,sizeof(t_tof->xtofpos));
            memcpy(t_tof->ytofpos,tofoutput_.ytofpos,sizeof(t_tof->ytofpos));
            memcpy(t_tof->xtr_tof,tofoutput_.xtr_tof,sizeof(t_tof->xtr_tof));
            memcpy(t_tof->ytr_tof,tofoutput_.ytr_tof,sizeof(t_tof->ytr_tof));
            //
            {
              Float_t xtof_temp[6]={100.,100.,100.,100.,100.,100.};
              Float_t ytof_temp[6]={100.,100.,100.,100.,100.,100.};

              if(t_tof->xtofpos[0]<100. && t_tof->ytofpos[0]<100.){
                xtof_temp[1]=t_tof->xtofpos[0];
                ytof_temp[0]=t_tof->ytofpos[0];
              }else if(t_tof->xtofpos[0]>=100. && t_tof->ytofpos[0]<100.){
                ytof_temp[0]=t_tof->ytofpos[0];
                tof->GetPaddleGeometry(0,(Int_t)log2(tof->tof_j_flag[0]),xleft, xright, yleft, yright);
                xtof_temp[1]=xleft+2.55;
              }else if(t_tof->ytofpos[0]>=100. && t_tof->xtofpos[0]<100.){
                xtof_temp[1]=t_tof->xtofpos[0];
                tof->GetPaddleGeometry(1,(Int_t)log2(tof->tof_j_flag[1]),xleft, xright, yleft, yright);
                ytof_temp[0]=yleft+2.75;
              }

              if(t_tof->xtofpos[1]<100. && t_tof->ytofpos[1]<100.){
                xtof_temp[2]=t_tof->xtofpos[1];
                ytof_temp[3]=t_tof->ytofpos[1];
              }else if(t_tof->xtofpos[1]>=100. && t_tof->ytofpos[1]<100.){
                ytof_temp[3]=t_tof->ytofpos[1];
                tof->GetPaddleGeometry(3,(Int_t)log2(tof->tof_j_flag[3]),xleft, xright, yleft, yright);
                xtof_temp[2]=xleft+4.5;
              }else if(t_tof->ytofpos[1]>=100. && t_tof->xtofpos[1]<100.){
                xtof_temp[2]=t_tof->xtofpos[1];
                tof->GetPaddleGeometry(2,(Int_t)log2(tof->tof_j_flag[2]),xleft, xright, yleft, yright);
                ytof_temp[3]=yleft+3.75;
              }

              if(t_tof->xtofpos[2]<100. && t_tof->ytofpos[2]<100.){
                xtof_temp[5]=t_tof->xtofpos[2];
                ytof_temp[4]=t_tof->ytofpos[2];
              }else if(t_tof->xtofpos[2]>=100. && t_tof->ytofpos[2]<100.){
                ytof_temp[4]=t_tof->ytofpos[2];
                tof->GetPaddleGeometry(4,(Int_t)log2(tof->tof_j_flag[4]),xleft, xright, yleft, yright);
                xtof_temp[5]=xleft+3;
              }else if(t_tof->ytofpos[2]>=100. && t_tof->xtofpos[2]<100.){
                xtof_temp[5]=t_tof->xtofpos[2];
                tof->GetPaddleGeometry(5,(Int_t)log2(tof->tof_j_flag[5]),xleft, xright, yleft, yright);
                ytof_temp[4]=yleft+2.5;
              }
              //
              tofdedx->Process(atime,t_tof->beta[12], (Float_t *)xtof_temp,(Float_t *)ytof_temp);
              t_tof->npmtadc = 0;
              for (Int_t hh=0; hh<12;hh++){
                for (Int_t kk=0; kk<4;kk++){
                  pmt_id = tof->GetPMTid(kk,hh);
                  Int_t Iplane=-1;
                  Int_t Ipaddle=-1;
                  tof->GetPMTPaddle(pmt_id, Iplane, Ipaddle);
                  tof->GetPaddleGeometry(Iplane,Ipaddle,xleft,xright,yleft,yright);
                  if (tofEvent->tdc[kk][hh] < 4095 || tofEvent->adc[kk][hh] < 4095 || tofinput_.tdc[hh][kk] < 4095 || tofinput_.adc[hh][kk] < 4095 ) {
                    if ( tofdedx->GetdEdx_pmt(pmt_id)>-1. && (inter_dedx[pmt_id]+slope_dedx[pmt_id]*tofdedx->GetdEdx_pmt(pmt_id)) > 0. &&((xtof_temp[Iplane]>=xleft&&xtof_temp[Iplane]<=xright) || (ytof_temp[Iplane]>=yleft&&ytof_temp[Iplane]<=yright)) ){  

                      t_tof->dedx.AddAt((inter_dedx[pmt_id]+slope_dedx[pmt_id]*tofdedx->GetdEdx_pmt(pmt_id)),t_tof->npmtadc);// RC new dE/dx II order correction

                      t_tof->pmtadc.AddAt(pmt_id,t_tof->npmtadc);
                      t_tof->adcflag.AddAt(0,t_tof->npmtadc); // gf: Jan 09/07
                      t_tof->npmtadc++;
                    }
                  }
                }
              }
            }
            new(t[ntrkentry]) ToFTrkVar(*t_tof);
            ntrkentry++;	
            t_tof->Clear();
            t_pmt->Clear();
            //
            for (Int_t gg=0; gg<4;gg++){
              for (Int_t hh=0; hh<12;hh++){
                // new WM
                if ( tofoutput_.tdc_c[hh][gg] < 4095 || (0xFFF & tofEvent->adc[gg][hh]) < 4095  || (0xFFF & tofEvent->tdc[gg][hh]) < 4095 ){	   
                  t_pmt->pmt_id = tof->GetPMTid(gg,hh);
                  t_pmt->tdc_tw = tofoutput_.tdc_c[hh][gg];
                  t_pmt->adc = (Float_t)(0xFFF & tofEvent->adc[gg][hh]);
                  t_pmt->tdc = (Float_t)(0xFFF & tofEvent->tdc[gg][hh]);
                  t_pmt->l0flag_adc = (Float_t)(tofEvent->adc[gg][hh]>>12);
                  t_pmt->l0flag_tdc = (Float_t)(tofEvent->tdc[gg][hh]>>12);
                  if ( t_pmt->l0flag_adc || t_pmt->l0flag_tdc ) warning |= 1 << 0; 
                  //
                  new(tpmt[npmtentry]) ToFPMT(*t_pmt);
                  npmtentry++;	
                  t_pmt->Clear();
                }
              }
            }
            //
            if ( debug ) printf(" ATIME %u re %u \n",atime,(UInt_t)re);
            //
            // Calculate track-related variables 
            //

            //
            // Run over tracks - standard algorithm
            //
            for(Int_t nt=0; nt < trk->ntrk(); nt++){  
              //
              TrkTrack *ptt = trk->GetStoredTrack(nt); 
              //
              // Copy the alpha vector in the input structure
              //
              for (Int_t e = 0; e < 5 ; e++){
                tofinput_.al_pp[e] = ptt->al[e];
              }
              // new input for 9th reduction: tracker dEdx
              tofinput_.trkmip = ptt->GetDEDX();
              //
              // Get tracker related variables for this track
              //
              toftrk();
              //
              // Copy values in the class from the structure (we need to use a temporary class to store variables).
              //
              t_tof->npmttdc = 0;
              for (Int_t hh=0; hh<12;hh++){
                for (Int_t kk=0; kk<4;kk++){
                  if ( tofoutput_.tofmask[hh][kk] != 0 ){
                    pmt_id = tof->GetPMTid(kk,hh);
                    t_tof->pmttdc.AddAt(pmt_id,t_tof->npmttdc);
                    t_tof->tdcflag.AddAt(tofoutput_.tdcflag[hh][kk],t_tof->npmttdc); // gf: Jan 09/07
                    t_tof->npmttdc++;
                  }
                }
              }
              for (Int_t kk=0; kk<13;kk++){
                t_tof->beta[kk] = tofoutput_.beta_a[kk];	
              }
              memcpy(t_tof->xtofpos,tofoutput_.xtofpos,sizeof(t_tof->xtofpos));
              memcpy(t_tof->ytofpos,tofoutput_.ytofpos,sizeof(t_tof->ytofpos));
              memcpy(t_tof->xtr_tof,tofoutput_.xtr_tof,sizeof(t_tof->xtr_tof));
              memcpy(t_tof->ytr_tof,tofoutput_.ytr_tof,sizeof(t_tof->ytr_tof));
              //
              tofdedx->Process(atime,t_tof->beta[12], (Float_t *)t_tof->xtr_tof,(Float_t *)t_tof->ytr_tof);
              t_tof->npmtadc = 0;
              for (Int_t hh=0; hh<12;hh++){
                for (Int_t kk=0; kk<4;kk++){
                  pmt_id = tof->GetPMTid(kk,hh);
                  Int_t Iplane=-1;
                  Int_t Ipaddle=-1;
                  Int_t IpaddleT=-1;
                  tof->GetPMTPaddle(pmt_id, Iplane, Ipaddle);
                  IpaddleT=tof->GetPaddleIdOfTrack(t_tof->xtr_tof[Iplane],t_tof->ytr_tof[Iplane], Iplane,0.0);
                  if ( debug ) printf(" 1nt %i pmt_id %i npmtadc %i dedx %f dedx slope %f dedx inter %f\n",nt,pmt_id,t_tof->npmtadc,(inter_dedx[pmt_id]+slope_dedx[pmt_id]*tofdedx->GetdEdx_pmt(pmt_id)),inter_dedx[pmt_id],slope_dedx[pmt_id]);
                  if (tofEvent->tdc[kk][hh] < 4095 || tofEvent->adc[kk][hh] < 4095 || tofinput_.tdc[hh][kk] < 4095 || tofinput_.adc[hh][kk] < 4095 ) {
                    if ( tofdedx->GetdEdx_pmt(pmt_id) > -1. && (inter_dedx[pmt_id]+slope_dedx[pmt_id]*tofdedx->GetdEdx_pmt(pmt_id)) > 0. && Ipaddle==IpaddleT ){ 
                      t_tof->dedx.AddAt((inter_dedx[pmt_id]+slope_dedx[pmt_id]*tofdedx->GetdEdx_pmt(pmt_id)),t_tof->npmtadc);// RC new dE/dx II order correction
                      if ( debug ) printf(" 2nt %i npmtadc %i dedx %f dedx slope %f dedx inter %f\n",nt,t_tof->npmtadc,(inter_dedx[pmt_id]+slope_dedx[pmt_id]*tofdedx->GetdEdx_pmt(pmt_id)),inter_dedx[pmt_id],slope_dedx[pmt_id]);
                      t_tof->pmtadc.AddAt(pmt_id,t_tof->npmtadc);
                      t_tof->adcflag.AddAt(0,t_tof->npmtadc); // gf: Jan 09/07
                      t_tof->npmtadc++;
                    }
                  }      
                }
              }
              //
              // Store the tracker track number in order to be sure to have shyncronized data during analysis
              //
              t_tof->trkseqno = nt;
              //
              // create a new object for this event with track-related variables
              //
              new(t[ntrkentry]) ToFTrkVar(*t_tof);
              ntrkentry++;	
              t_tof->Clear();
              //
            } // loop on all the tracks
            //
            // Code for extended tracking algorithm: 
            //
            //
            // Run over tracks - nuclei algorithm
            //
            if ( hasNucleiTrk ){
              Int_t ttentry = 0;
              for(Int_t nt=0; nt < tcNucleiTrk->GetEntries(); nt++){  
                //
                TrkTrack *ptt = (TrkTrack*)(tcNucleiTrk->At(nt)); 
                //
                // Copy the alpha vector in the input structure
                //
                for (Int_t e = 0; e < 5 ; e++){
                  tofinput_.al_pp[e] = ptt->al[e];
                }
                // new input for 9th reduction: tracker dEdx
                tofinput_.trkmip = ptt->GetDEDX();
                //
                // Get tracker related variables for this track
                //
                toftrk();
                //
                // Copy values in the class from the structure (we need to use a temporary class to store variables).
                //
                t_tof->npmttdc = 0;
                for (Int_t hh=0; hh<12;hh++){
                  for (Int_t kk=0; kk<4;kk++){
                    if ( tofoutput_.tofmask[hh][kk] != 0 ){
                      pmt_id = tof->GetPMTid(kk,hh);
                      t_tof->pmttdc.AddAt(pmt_id,t_tof->npmttdc);
                      t_tof->tdcflag.AddAt(tofoutput_.tdcflag[hh][kk],t_tof->npmttdc); // gf: Jan 09/07
                      t_tof->npmttdc++;
                    }
                  }
                }
                for (Int_t kk=0; kk<13;kk++){
                  t_tof->beta[kk] = tofoutput_.beta_a[kk];	
                }
                memcpy(t_tof->xtofpos,tofoutput_.xtofpos,sizeof(t_tof->xtofpos));
                memcpy(t_tof->ytofpos,tofoutput_.ytofpos,sizeof(t_tof->ytofpos));
                memcpy(t_tof->xtr_tof,tofoutput_.xtr_tof,sizeof(t_tof->xtr_tof));
                memcpy(t_tof->ytr_tof,tofoutput_.ytr_tof,sizeof(t_tof->ytr_tof));
                //
                tofdedx->Process(atime,t_tof->beta[12], (Float_t *)t_tof->xtr_tof,(Float_t *)t_tof->ytr_tof);
                t_tof->npmtadc = 0;
                for (Int_t hh=0; hh<12;hh++){
                  for (Int_t kk=0; kk<4;kk++){
                    pmt_id = tof->GetPMTid(kk,hh);
                    Int_t Iplane=-1;
                    Int_t Ipaddle=-1;
                    Int_t IpaddleT=-1;
                    tof->GetPMTPaddle(pmt_id, Iplane, Ipaddle);
                    IpaddleT=tof->GetPaddleIdOfTrack(t_tof->xtr_tof[Iplane],t_tof->ytr_tof[Iplane], Iplane,0.0);
                    if ( debug ) printf(" 1nt %i pmt_id %i npmtadc %i dedx %f dedx slope %f dedx inter %f\n",nt,pmt_id,t_tof->npmtadc,(inter_dedx[pmt_id]+slope_dedx[pmt_id]*tofdedx->GetdEdx_pmt(pmt_id)),inter_dedx[pmt_id],slope_dedx[pmt_id]);
                    if (tofEvent->tdc[kk][hh] < 4095 || tofEvent->adc[kk][hh] < 4095 || tofinput_.tdc[hh][kk] < 4095 || tofinput_.adc[hh][kk] < 4095 ) {
                      if ( tofdedx->GetdEdx_pmt(pmt_id) > -1. && (inter_dedx[pmt_id]+slope_dedx[pmt_id]*tofdedx->GetdEdx_pmt(pmt_id)) > 0. && Ipaddle==IpaddleT ){ 
                        t_tof->dedx.AddAt((inter_dedx[pmt_id]+slope_dedx[pmt_id]*tofdedx->GetdEdx_pmt(pmt_id)),t_tof->npmtadc);// RC new dE/dx II order correction
                        if ( debug ) printf(" 2nt %i npmtadc %i dedx %f dedx slope %f dedx inter %f\n",nt,t_tof->npmtadc,(inter_dedx[pmt_id]+slope_dedx[pmt_id]*tofdedx->GetdEdx_pmt(pmt_id)),inter_dedx[pmt_id],slope_dedx[pmt_id]);
                        t_tof->pmtadc.AddAt(pmt_id,t_tof->npmtadc);
                        t_tof->adcflag.AddAt(0,t_tof->npmtadc); // gf: Jan 09/07
                        t_tof->npmtadc++;
                      }
                    }      
                  }
                }
                //
                // Store the tracker track number in order to be sure to have shyncronized data during analysis
                //
                t_tof->trkseqno = nt;
                //
                // create a new object for this event with track-related variables
                //
                TClonesArray &tt1 = *ttofNucleiTrk;
                new(tt1[ttentry]) ToFTrkVar(*t_tof);
                ttentry++;	
                t_tof->Clear();
                //
              } // loop on all the tracks, nuclei algorithm
            }
            //
            // Run over tracks - extended nuclei algorithm
            //
            if ( hasExtNucleiTrk ){
              Int_t ttentry = 0;
              for(Int_t nt=0; nt < tcExtNucleiTrk->GetEntries(); nt++){  
                //
                ExtTrack *ptt = (ExtTrack*)(tcExtNucleiTrk->At(nt)); 
                //
                // Copy the alpha vector in the input structure
                //
                for (Int_t e = 0; e < 5 ; e++){
                  tofinput_.al_pp[e] = ptt->al[e];
                }
                // new input for 9th reduction: tracker dEdx
                tofinput_.trkmip = ptt->GetDEDX();
                //
                // Get tracker related variables for this track
                //
                toftrk();
                //
                // Copy values in the class from the structure (we need to use a temporary class to store variables).
                //
                t_tof->npmttdc = 0;
                for (Int_t hh=0; hh<12;hh++){
                  for (Int_t kk=0; kk<4;kk++){
                    if ( tofoutput_.tofmask[hh][kk] != 0 ){
                      pmt_id = tof->GetPMTid(kk,hh);
                      t_tof->pmttdc.AddAt(pmt_id,t_tof->npmttdc);
                      t_tof->tdcflag.AddAt(tofoutput_.tdcflag[hh][kk],t_tof->npmttdc); // gf: Jan 09/07
                      t_tof->npmttdc++;
                    }
                  }
                }
                for (Int_t kk=0; kk<13;kk++){
                  t_tof->beta[kk] = tofoutput_.beta_a[kk];	
                }
                memcpy(t_tof->xtofpos,tofoutput_.xtofpos,sizeof(t_tof->xtofpos));
                memcpy(t_tof->ytofpos,tofoutput_.ytofpos,sizeof(t_tof->ytofpos));
                memcpy(t_tof->xtr_tof,tofoutput_.xtr_tof,sizeof(t_tof->xtr_tof));
                memcpy(t_tof->ytr_tof,tofoutput_.ytr_tof,sizeof(t_tof->ytr_tof));
                //
                tofdedx->Process(atime,t_tof->beta[12], (Float_t *)t_tof->xtr_tof,(Float_t *)t_tof->ytr_tof);
                t_tof->npmtadc = 0;
                for (Int_t hh=0; hh<12;hh++){
                  for (Int_t kk=0; kk<4;kk++){
                    pmt_id = tof->GetPMTid(kk,hh);
                    Int_t Iplane=-1;
                    Int_t Ipaddle=-1;
                    Int_t IpaddleT=-1;
                    tof->GetPMTPaddle(pmt_id, Iplane, Ipaddle);
                    IpaddleT=tof->GetPaddleIdOfTrack(t_tof->xtr_tof[Iplane],t_tof->ytr_tof[Iplane], Iplane,0.0);
                    if ( debug ) printf(" 1nt %i pmt_id %i npmtadc %i dedx %f dedx slope %f dedx inter %f\n",nt,pmt_id,t_tof->npmtadc,(inter_dedx[pmt_id]+slope_dedx[pmt_id]*tofdedx->GetdEdx_pmt(pmt_id)),inter_dedx[pmt_id],slope_dedx[pmt_id]);
                    if (tofEvent->tdc[kk][hh] < 4095 || tofEvent->adc[kk][hh] < 4095 || tofinput_.tdc[hh][kk] < 4095 || tofinput_.adc[hh][kk] < 4095 ) {
                      if ( tofdedx->GetdEdx_pmt(pmt_id) > -1. && (inter_dedx[pmt_id]+slope_dedx[pmt_id]*tofdedx->GetdEdx_pmt(pmt_id)) > 0. && Ipaddle==IpaddleT ){ 
                        t_tof->dedx.AddAt((inter_dedx[pmt_id]+slope_dedx[pmt_id]*tofdedx->GetdEdx_pmt(pmt_id)),t_tof->npmtadc);// RC new dE/dx II order correction
                        if ( debug ) printf(" 2nt %i npmtadc %i dedx %f dedx slope %f dedx inter %f\n",nt,t_tof->npmtadc,(inter_dedx[pmt_id]+slope_dedx[pmt_id]*tofdedx->GetdEdx_pmt(pmt_id)),inter_dedx[pmt_id],slope_dedx[pmt_id]);
                        t_tof->pmtadc.AddAt(pmt_id,t_tof->npmtadc);
                        t_tof->adcflag.AddAt(0,t_tof->npmtadc); // gf: Jan 09/07
                        t_tof->npmtadc++;
                      }
                    }      
                  }
                }
                //
                // Store the tracker track number in order to be sure to have shyncronized data during analysis
                //
                t_tof->trkseqno = nt;
                //
                // create a new object for this event with track-related variables
                //
                TClonesArray &tt2 = *ttofExtNucleiTrk;
                new(tt2[ttentry]) ToFTrkVar(*t_tof);
                ttentry++;	
                t_tof->Clear();
                //
              } // loop on all the tracks, extended nuclei algorithm
            }
            //
            // Run over tracks - extended algorithm
            //
            if ( hasExtTrk ){
              Int_t ttentry = 0;
              for(Int_t nt=0; nt < tcExtTrk->GetEntries(); nt++){  
                //
                ExtTrack *ptt = (ExtTrack*)(tcExtTrk->At(nt)); 
                //
                // Copy the alpha vector in the input structure
                //
                for (Int_t e = 0; e < 5 ; e++){
                  tofinput_.al_pp[e] = ptt->al[e];
                }
                // new input for 9th reduction: tracker dEdx
                tofinput_.trkmip = ptt->GetDEDX();
                //
                // Get tracker related variables for this track
                //
                toftrk();
                //
                // Copy values in the class from the structure (we need to use a temporary class to store variables).
                //
                t_tof->npmttdc = 0;
                for (Int_t hh=0; hh<12;hh++){
                  for (Int_t kk=0; kk<4;kk++){
                    if ( tofoutput_.tofmask[hh][kk] != 0 ){
                      pmt_id = tof->GetPMTid(kk,hh);
                      t_tof->pmttdc.AddAt(pmt_id,t_tof->npmttdc);
                      t_tof->tdcflag.AddAt(tofoutput_.tdcflag[hh][kk],t_tof->npmttdc); // gf: Jan 09/07
                      t_tof->npmttdc++;
                    }
                  }
                }
                for (Int_t kk=0; kk<13;kk++){
                  t_tof->beta[kk] = tofoutput_.beta_a[kk];	
                }
                memcpy(t_tof->xtofpos,tofoutput_.xtofpos,sizeof(t_tof->xtofpos));
                memcpy(t_tof->ytofpos,tofoutput_.ytofpos,sizeof(t_tof->ytofpos));
                memcpy(t_tof->xtr_tof,tofoutput_.xtr_tof,sizeof(t_tof->xtr_tof));
                memcpy(t_tof->ytr_tof,tofoutput_.ytr_tof,sizeof(t_tof->ytr_tof));
                //
                tofdedx->Process(atime,t_tof->beta[12], (Float_t *)t_tof->xtr_tof,(Float_t *)t_tof->ytr_tof);
                t_tof->npmtadc = 0;
                for (Int_t hh=0; hh<12;hh++){
                  for (Int_t kk=0; kk<4;kk++){
                    pmt_id = tof->GetPMTid(kk,hh);
                    Int_t Iplane=-1;
                    Int_t Ipaddle=-1;
                    Int_t IpaddleT=-1;
                    tof->GetPMTPaddle(pmt_id, Iplane, Ipaddle);
                    IpaddleT=tof->GetPaddleIdOfTrack(t_tof->xtr_tof[Iplane],t_tof->ytr_tof[Iplane], Iplane,0.0);
                    if ( debug ) printf(" 1nt %i pmt_id %i npmtadc %i dedx %f dedx slope %f dedx inter %f\n",nt,pmt_id,t_tof->npmtadc,(inter_dedx[pmt_id]+slope_dedx[pmt_id]*tofdedx->GetdEdx_pmt(pmt_id)),inter_dedx[pmt_id],slope_dedx[pmt_id]);
                    if (tofEvent->tdc[kk][hh] < 4095 || tofEvent->adc[kk][hh] < 4095 || tofinput_.tdc[hh][kk] < 4095 || tofinput_.adc[hh][kk] < 4095 ) {
                      if ( tofdedx->GetdEdx_pmt(pmt_id) > -1. && (inter_dedx[pmt_id]+slope_dedx[pmt_id]*tofdedx->GetdEdx_pmt(pmt_id)) > 0. && Ipaddle==IpaddleT ){ 
                        t_tof->dedx.AddAt((inter_dedx[pmt_id]+slope_dedx[pmt_id]*tofdedx->GetdEdx_pmt(pmt_id)),t_tof->npmtadc);// RC new dE/dx II order correction
                        if ( debug ) printf(" 2nt %i npmtadc %i dedx %f dedx slope %f dedx inter %f\n",nt,t_tof->npmtadc,(inter_dedx[pmt_id]+slope_dedx[pmt_id]*tofdedx->GetdEdx_pmt(pmt_id)),inter_dedx[pmt_id],slope_dedx[pmt_id]);
                        t_tof->pmtadc.AddAt(pmt_id,t_tof->npmtadc);
                        t_tof->adcflag.AddAt(0,t_tof->npmtadc); // gf: Jan 09/07
                        t_tof->npmtadc++;
                      }
                    }      
                  }
                }
                //
                // Store the tracker track number in order to be sure to have shyncronized data during analysis
                //
                t_tof->trkseqno = nt;
                //
                // create a new object for this event with track-related variables
                //
                TClonesArray &tt3 = *ttofExtTrk;
                new(tt3[ttentry]) ToFTrkVar(*t_tof);
                ttentry++;	
                t_tof->Clear();
                //
              } // loop on all the tracks, extended algorithm
            }
            
          } // if !l1only
          //
          tof->unpackError = tofEvent->unpackError;

          a = 0;
          b = 0;
          if ( !tof->checkPMTpatternPMThit(trg, a, b) ) warning |= 1 << 1; 
          if ( !tof->checkPMTpmttrig(trg) ) warning |= 1 << 2; 
          if ( !trg->checkPMTpatterntrig() ) warning |= 1 << 3; 
          tof->unpackWarning = warning;

          if ( defcal ){
            tof->default_calib = 1;
          } else {
            tof->default_calib = 0;
          }
          //
          // Fill the rootple 
          //
          toft->Fill();
          //    
          //
          //
          delete t_tof;
          //
          //
          //
    jumpev:
          if ( !debug ) debug = false;
          //
    }
    //
    // Here you may want to clear some variables before processing another run  
    //
    delete dbtime;
  } // process all the runs
  //
  if ( verbose ) printf("\n Finished processing data \n");
  //
 closeandexit:
  //
  // we have finished processing the run(s). If we processed a single run now we must copy all the events after our run from the old tree to the new one and delete the old tree.
  //
  if ( !reprocall && reproc && code >= 0 ){
    if ( totfileentries > noaftrun ){
      if ( verbose ) printf("\n Post-processing: copying events from the old tree after the processed run\n");   
      if ( verbose ) printf(" Copying %i events in the file which are after the end of the run %i \n",(int)(totfileentries-noaftrun),(int)run);
      if ( verbose ) printf(" Start copying at event number %i end copying at event number %i \n",(int)noaftrun,(int)totfileentries);
      for (UInt_t j = noaftrun; j < totfileentries; j++ ){
	//
	// Get entry from old tree
	//
	if ( toftclone->GetEntry(j) <= 0 ) throw -36;
	//
	// copy tofclone to tof
	//
	memcpy(&tof,&tofclone,sizeof(tofclone));// EM reprocessing bug fixed 
	//
	// Fill entry in the new tree
	//
	toft->Fill();// EM reprocessing bug fixed 
      };
      if ( verbose ) printf(" Finished successful copying!\n");
    };
  };
  //
  // Close files, delete old tree(s), write and close level2 file 
  //
  if ( l0File ) l0File->Close();
  if ( tempfile ) tempfile->Close();            
  if ( myfold ) gSystem->Unlink(tempname.str().c_str());
  //
  if ( code < 0 && verbose ) printf("\n TOF - ERROR: an error occurred, try to save anyway...\n");
  if ( verbose ) printf("\n Writing and closing rootple\n");
  if ( toft ) toft->SetName("ToF");    
  if ( file ){
    file->cd();
    if ( toft ) toft->Write(0, TObject::kOverwrite); // 10RED bug fixed
  };
  //
  if ( myfold ) gSystem->Unlink(toffolder.str().c_str());
  //
  // the end
  //
  if ( tcNucleiTrk ){
    tcNucleiTrk->Delete();
    delete tcNucleiTrk;
    tcNucleiTrk = NULL;
  }
  if ( tcExtNucleiTrk ){
    tcExtNucleiTrk->Delete();
    delete tcExtNucleiTrk;
    tcExtNucleiTrk = NULL;
  }
  if ( tcExtTrk ){
    tcExtTrk->Delete();
    delete tcExtTrk;
    tcExtTrk = NULL;
  }
  //
  if ( verbose ) printf("\n Exiting...\n");
  //
  if ( tofdedx ) delete tofdedx;
  if ( glroot ) delete glroot;
  if ( glparam ) delete glparam;
  if ( runinfo ) runinfo->Close();    
  if ( runinfo ) delete runinfo; 
  //
  if ( code < 0 ) throw code;
  if ( debug ) file->ls();
  return(code);
}
