//
// C/C++ headers
//
#include <iostream>
#include <sstream>
//
// ROOT headers
//
#include <TTimeStamp.h>
#include <TString.h>
#include <TSQLServer.h>
#include <TFile.h>
#include <TSystem.h>
#include <TStopwatch.h>
#include <TObjectTable.h>
//
#include <GLTables.h>
//
// Detector's package headers
//
#include <RunInfoCore.h>
#include <TrkCore.h>
#include <TrigCore.h>
#include <ToFCore.h>
#include <CaloCore.h>
#include <AcCore.h>
#include <S4Core.h>
#include <NDCore.h>
#include <OrbitalInfoCore.h>
#include <RunInfo.h>
//
using namespace std;
//
GL_TABLES *glt = NULL;
//
//
#include <DarthVaderVerl2.h>
//
// Usage subroutine
//
void usage(){
  printf("\nUsage:\n");
  printf("\n DarthVader [ options ] -idRun ID_RUN [+-all] [+-detector [ detector options ] ] \n");
  printf("\n Options are: \n\n");
  printf(" --version         print informations about compilation and exit\n");
  printf(" -h || --help      print this help and exit \n");
  printf(" -v || --verbose   be verbose [default]\n");
  printf(" -s || --silent    print nothing on STDOUT\n");
  printf(" -c || --clean     remove file if exiting with errors\n");
  printf(" -b || --benchmark perform and print a benchmark test\n");
  printf(" -r || --reprocess force running on existing file [default: exit with error, NB: DEFAULT CHANGED since 10RED!!]\n");
  printf(" -n || --new-fit   use new fitting algorithm [default]\n");
  printf(" --no-new-fit      use only standard (up to 9RED) fitting algorithm\n");
  printf(" --force-TRK       force TRK and CAL/TOF simultaneous reprocessing (use only if you know the meaning! could crash!)\n");
  printf(" -auto || -AUTO    exclude from processing detector which are NOT in the acquisition\n");
  printf(" -zerofill         if a detector is not in the acquisition the routine is called anyway \n");
  printf("                   but all detector's data will be marked as bad [default]\n");
  printf(" -tedious          exit with error if a detector is not in the acquisition and \n");
  printf("                   it has not been excluded from processing\n");
  printf(" -host             name of the DB host [default = $PAM_DBHOST or mysql://localhost/pamelaprod]\n");
  printf(" -user             username for the DB connection [default = $PAM_DBUSER or \"anonymous\"] \n");
  printf(" -psw              password for the DB connection [default = $PAM_DBPSW or \"\"]\n");
  printf(" -idRun ID_RUN     ID number (from the DB) of the run to be processed \n");
  printf(" -processFile file output filename [default ID_RUN.Level2.root]\n");
  printf(" +all || +ALL      call all detectors software [default]\n");
  printf(" -all || -ALL      call nothing\n");
  printf(" +detector         process detector; detector can be: TOF,TRK,CAL,TRG,ORB,S4,ND,AC,RUN\n");
  printf(" -detector         do not process detector (as above)\n");
  printf("                   detector options must be included in square parenthesis with spaces, for example:\n");
  printf("                   +CAL [ --verbose -g ] +TRK [ -v --level1 ] \n");  
  printf("\n Examples: \n");
  printf(" Standard call:\n            DarthVader -idRun 1085 \n");
  printf(" Process only RunInfo and Tracker (be verbose for tracker):\n            DarthVader -idRun 1085 -all +RUN +TRK [ --verbose ] \n");
  printf(" Process all and be verbose for calorimeter:\n            DarthVader -idRun 1085 +CAL [ --verbose ] \n\n");
  printf(" Set Tracker to work with simulated data:\n            DarthVader -idRun 1085 +TRK [ --simu ] \n\n");
};

//
// Here the main
//
int main(int numinp, char *inps[]){
  //
  // Variables booking
  //
  //
  // benchmarck variables
  //
  TStopwatch timer;
  TStopwatch dvtimer;
  dvtimer.Start(kTRUE);
  UInt_t nevents = 0;
  UInt_t nruns = 0;
  Double_t runtime = 0.;
  Double_t cruntime = 0.;
  Double_t trktime = 0.;
  Double_t ctrktime = 0.;
  Double_t caltime = 0.;
  Double_t ccaltime = 0.;
  Double_t caltime1 = 0.;
  Double_t ccaltime1 = 0.;
  Double_t toftime = 0.;
  Double_t ctoftime = 0.;
  Double_t toftime1 = 0.;
  Double_t ctoftime1 = 0.;
  Double_t trgtime = 0.;
  Double_t ctrgtime = 0.;
  Double_t actime = 0.;
  Double_t cactime = 0.;
  Double_t s4time = 0.;
  Double_t cs4time = 0.;
  Double_t ndtime = 0.;
  Double_t cndtime = 0.;
  Double_t orbtime = 0.;
  Double_t corbtime = 0.;
  Double_t dvtime = 0.;
  Double_t cdvtime = 0.;
  //
  TString message;
  int nul = 0;
  Int_t error = 0;
  //
  Int_t CALSGN = 0;
  Int_t CALSGN1 = 0;
  Int_t TRKSGN = 0;
  Int_t TRGSGN = 0;
  Int_t TOFSGN = 0;
  Int_t TOFSGN1 = 0;
  Int_t RUNSGN = 0;
  Int_t ORBSGN = 0;
  Int_t ACSGN = 0;
  Int_t S4SGN = 0;
  Int_t NDSGN = 0;
  Int_t DVSGN = 0;
  //
  UInt_t NQRUN = 0;
  UInt_t NQTRK = 0;
  UInt_t NQCAL = 0;
  UInt_t NQCAL1 = 0;
  UInt_t NQTOF = 0;
  UInt_t NQTOF1 = 0;
  UInt_t NQORB = 0;
  UInt_t NQTRG = 0;
  UInt_t NQAC = 0;
  UInt_t NQND = 0;
  UInt_t NQS4 = 0;
  UInt_t NQTOT = 0;
  //
  Bool_t autom = false;
  Bool_t zerofill = true;
  Bool_t tedious = false;
  Bool_t remfile = false;
  Bool_t debug = false;
  Bool_t beverbose = true;
  Bool_t givenid = false;
  Bool_t bench = false;
  Bool_t reprocess = false;
  Bool_t newfit = true;
  Bool_t forcetrk = false;
  Bool_t CAL = true;
  Bool_t TRK = true;
  Bool_t TRG = true;
  Bool_t TOF = true;
  Bool_t S4 = true;
  Bool_t ND = true;
  Bool_t AC = true;
  Bool_t ORB = true;
  Bool_t RUN = true;  
  //
  Int_t calargc = 0;
  char *calargv[50];
  Int_t trkargc = 0;
  char *trkargv[50];
  Int_t tofargc = 0;
  char *tofargv[50];
  Int_t trgargc = 0;
  char *trgargv[50];
  Int_t orbargc = 0;
  char *orbargv[50];
  Int_t runargc = 0;
  char *runargv[50];
  Int_t acargc = 0;
  char *acargv[50];
  Int_t s4argc = 0;
  char *s4argv[50];
  Int_t ndargc = 0;
  char *ndargv[50];
  //
  //
  //
  UInt_t run = 0;
  //
  TString filename;
  TString outDir =  gSystem->WorkingDirectory(); 
  //
  TSQLServer *dbc = 0;
  TString host = "mysql://localhost/pamelaprod";
  TString user = "anonymous";
  TString psw = "";
  //  
  //
  const char *pamdbhost=gSystem->Getenv("PAM_DBHOST");
  const char *pamdbuser=gSystem->Getenv("PAM_DBUSER");
  const char *pamdbpsw=gSystem->Getenv("PAM_DBPSW");
  if ( !pamdbhost ) pamdbhost = "";
  if ( !pamdbuser ) pamdbuser = "";
  if ( !pamdbpsw ) pamdbpsw = "";
  if ( strcmp(pamdbhost,"") ) host = pamdbhost;
  if ( strcmp(pamdbuser,"") ) user = pamdbuser;
  if ( strcmp(pamdbpsw,"") ) psw = pamdbpsw;
  //
  //
  TFile *processFile = 0;
  //
  // Checking input parameters
  //
  Int_t i = 0;
  try {
    if ( numinp > 1 ){
      while ( i < numinp ){
	Bool_t found = false;
	if ( !strcmp(inps[i],"--version") ){
	  DarthVaderInfo(true);
	  exit(0);
	};
	if ( !strcmp(inps[i],"-h") || !strcmp(inps[i],"--help") ){
	  usage();
	  exit(0);
	};
	if ( !strcmp(inps[i],"-idRun") ) {
	  if ( numinp-1 < i+1 ) {
	    usage();
	    throw -3;
	  };
	  i++;
	  found = true;
	  givenid = true;
	  run = atoll(inps[i]);	
	};
	if ( !strcmp(inps[i],"-processFile") ) {
	  if ( numinp-1 < i+1 ){
	    usage();
	    throw -3;
	  };
	  i++;
	  found = true;
	  filename = (TString)inps[i];	
	};
	if ( !strcmp(inps[i],"-outDir") ) {
	  if ( numinp-1 < i+1 ){
	    usage();
	    throw -3;
	  };
	  i++;
	  found = true;
	  outDir = (TString)inps[i];	
	};
	if ( !strcmp(inps[i],"-host") ) {
	  if ( numinp-1 < i+1 ){
	    usage();
	    throw -3;
	  };
	  i++;
	  found = true;
	  host = (TString)inps[i];	
	};
	if ( !strcmp(inps[i],"-user") ) {
	  if ( numinp-1 < i+1 ){
	    usage();
	    throw -3;
	  };
	  i++;
	  found = true;
	  user = (TString)inps[i];	
	};
	if ( !strcmp(inps[i],"-psw") ) {
	  if ( numinp-1 < i+1 ){
	    usage();
	    throw -3;
	  };
	  i++;
	  found = true;
	  psw = (TString)inps[i];	
	};
	if ( !strcmp(inps[i],"-v") || !strcmp(inps[i],"--verbose") ){
	  found = true;
	  beverbose = true;
	};
	if ( !strcmp(inps[i],"-c") || !strcmp(inps[i],"--clean")){
	  found = true;
	  remfile = true;
	};
	if ( !strcmp(inps[i],"-s") || !strcmp(inps[i],"--silent") ){
	  found = true;
	  beverbose = false;
	};
	if ( !strcmp(inps[i],"-g") || !strcmp(inps[i],"--debug") ){
	  debug = true;
	  found = true;
	};
	if ( !strcmp(inps[i],"-b") || !strcmp(inps[i],"--benchmark") ){
	  bench = true;
	  found = true;
	};
	if ( !strcmp(inps[i],"-r") || !strcmp(inps[i],"--reprocess") ){
	  reprocess = true;
	  found = true;
	};
	if ( !strcmp(inps[i],"-n") || !strcmp(inps[i],"--new-fit") ){
	  newfit = true;
	  found = true;
	};
	if ( !strcmp(inps[i],"--no-new-fit") ){
	  newfit = false;
	  found = true;
	};
	if ( !strcmp(inps[i],"--force-TRK") ){
	  forcetrk = true;
	  found = true;
	};
	if ( !strcmp(inps[i],"-auto") || !strcmp(inps[i],"-AUTO") ){
	  autom = true;
	  tedious = false;
	  zerofill = false;
	  found = true;
	};
	if ( !strcmp(inps[i],"-zerofill") ){
	  tedious = false;
	  autom = false;
	  zerofill = true;
	  found = true;
	};
	if ( !strcmp(inps[i],"-tedious") ){
	  tedious = true;
	  zerofill = false;
	  autom = false;
	  found = true;
	};
	//
	if ( !strcmp(inps[i],"-CAL") ) {
	  found = true;
	  CAL = false;
	};
	if ( !strcmp(inps[i],"-TRK") ) {
	  found = true;
	  TRK = false;
	};
	if ( !strcmp(inps[i],"-TOF") ) {
	  found = true;
	  TOF = false;
	};
	if ( !strcmp(inps[i],"-TRG") ) {
	  found = true;
	  TRG = false;
	};
	if ( !strcmp(inps[i],"-S4") ) {
	  found = true;
	  S4 = false;
	};
	if ( !strcmp(inps[i],"-ND") ) {
	  found = true;
	  ND = false;
	};
	if ( !strcmp(inps[i],"-AC") ) {
	  found = true;
	  AC = false;
	};
	if ( !strcmp(inps[i],"-RUN") ) {
	  found = true;
	  RUN = false;
	};
	if ( !strcmp(inps[i],"-ORB") ) {
	  found = true;
	  ORB = false;
	};
	//
	if ( !strcmp(inps[i],"-all") || !strcmp(inps[i],"-ALL") ) {
	  CAL = false;
	  ORB = false;
	  TRK = false;
	  TRG = false;
	  TOF = false;
	  S4 = false;
	  ND = false;
	  AC = false;
	  RUN = false;
	  found = true;
	};
	//
	if ( !strcmp(inps[i],"+all") || !strcmp(inps[i],"+ALL") ) {
	  CAL = true;
	  ORB = true;
	  TRK = true;
	  TRG = true;
	  TOF = true;
	  S4 = true;
	  ND = true;
	  AC = true;
	  RUN = true;
	  found = true;
	};
	//
	if ( !strcmp(inps[i],"+CAL") ) {
	  found = true;
	  CAL = true;
	  if ( numinp >= i+2 && !strcmp(inps[i+1],"[") ){
	    if ( numinp < i+2 ){
	      usage();
	      throw -3;
	    };
	    i += 2;	  
	    calargc = 0;
	    while ( strcmp(inps[i],"]") ){
	      calargv[calargc] = inps[i];
	      calargc++;
	      i++;
	      if ( i > numinp-1 ){
		usage();
		throw -3;
	      };
	    };
	  };
	};
	if ( !strcmp(inps[i],"+TRK") ) {
	  found = true;
	  TRK = true;
	  if ( numinp >= i+2 && !strcmp(inps[i+1],"[") ){
	    if ( numinp-1 < i+2 ){
	      usage();
	      throw -3;
	    };
	    i += 2;	  
	    trkargc = 0;
	    while ( strcmp(inps[i],"]") ){
	      trkargv[trkargc] = inps[i];
	      trkargc++;
	      i++;
	      if ( i > numinp-1 ){
		usage();
		throw -3;
	      };
	    };
	  };
	};
	if ( !strcmp(inps[i],"+TOF") ) {
	  found = true;
	  TOF = true;
	  if ( numinp >= i+2 && !strcmp(inps[i+1],"[") ){
	    i += 2;	  
	    tofargc = 0;
	    while ( strcmp(inps[i],"]") ){
	      tofargv[tofargc] = inps[i];
	      tofargc++;
	      i++;
	      if ( i > numinp-1 ){
		usage();
		throw -3;
	      };
	    };
	  };
	};
	if ( !strcmp(inps[i],"+TRG") ) {
	  found = true;
	  TRG = true;
	  if ( numinp >= i+2 && !strcmp(inps[i+1],"[") ){
	    i += 2;	  
	    trgargc = 0;
	    while ( strcmp(inps[i],"]") ){
	      trgargv[trgargc] = inps[i];
	      trgargc++;
	      i++;
	      if ( i > numinp-1 ){
		usage();
		throw -3;
	      };
	    };
	  };
	};
	if ( !strcmp(inps[i],"+ORB") ) {
	  found = true;
	  ORB = true;
	  if ( numinp >= i+2 && !strcmp(inps[i+1],"[") ){
	    i += 2;	  
	    orbargc = 0;
	    while ( strcmp(inps[i],"]") ){
	      orbargv[orbargc] = inps[i];
	      orbargc++;
	      i++;
	      if ( i > numinp-1 ){
		usage();
		throw -3;
	      };
	    };
	  };
	};
	if ( !strcmp(inps[i],"+RUN") ) {
	  found = true;
	  RUN = true;
	  if ( numinp >= i+2 && !strcmp(inps[i+1],"[") ){
	    i += 2;	  
	    runargc = 0;
	    while ( strcmp(inps[i],"]") ){
	      runargv[runargc] = inps[i];
	      runargc++;
	      i++;
	      if ( i > numinp-1 ){
		usage();
		throw -3;
	      };
	    };
	  };
	};
	if ( !strcmp(inps[i],"+AC") ) {
	  found = true;
	  AC = true;
	  if ( numinp >= i+2 && !strcmp(inps[i+1],"[") ){
	    i += 2;	  
	    acargc = 0;
	    while ( strcmp(inps[i],"]") ){
	      acargv[acargc] = inps[i];
	      acargc++;
	      i++;
	      if ( i > numinp-1 ){
		usage();
		throw -3;
	      };
	    };
	  };
	};
	if ( !strcmp(inps[i],"+S4") ) {
	  found = true;
	  S4 = true;
	  if ( numinp >= i+2 && !strcmp(inps[i+1],"[") ){
	    i += 2;	  
	    s4argc = 0;
	    while ( strcmp(inps[i],"]") ){
	      s4argv[s4argc] = inps[i];
	      s4argc++;
	      i++;
	      if ( i > numinp-1 ){
		usage();
		throw -3;
	      };
	    };
	  };
	};
	if ( !strcmp(inps[i],"+ND") ) {
	  found = true;
	  ND = true;
	  if ( numinp >= i+2 && !strcmp(inps[i+1],"[") ){
	    i += 2;	  
	    ndargc = 0;
	    while ( strcmp(inps[i],"]") ){
	      ndargv[ndargc] = inps[i];
	      ndargc++;
	      i++;
	      if ( i > numinp-1 ){
		usage();
		throw -3;
	      };
	    };
	  };
	};
	//
	if ( !found && i > 0 ){
	  usage();
	  printf(" Unknown input number %i, that is \"%s\" \n",i,inps[i]);
	  throw -22;
	};
	//
	i++;
      };
      //
    } else {
      //
      // no input parameters exit with error, we need at least the run id.
      //
      throw -1;
    };
    //
    // If not in verbose mode redirect to /dev/null the stdout and stderr
    //
    if ( !beverbose ){
      nul = open("/dev/null", O_CREAT | O_RDWR,S_IRUSR | S_IWUSR);
      dup2(nul,1);
      dup2(nul,2);
    };
    //
    // Check that an input run number has been given
    //
    if ( !givenid ) throw -1;
    //
    TString version = DarthVaderInfo(false);
    //
    // Start:
    //
    printf("\n Welcome to the PAMELA LEVEL2 flight software, version %s (The Ultimate Warrior)\n\n",version.Data());
    if ( run ){
      printf("\n Processing run number %u \n",run);
    } else {
      printf("\n Re-processing all runs?\n");
    }
    //
    // check tracker reprocessing
    //
    if ( TRK && reprocess ){
      printf(" WARNING: Tracker reprocessing can be incomplete and/or not working properly! \n");
      if ( ( CAL && TRK && reprocess ) || ( TOF && TRK && reprocess ) ){
        printf(" ERROR: cannot reprocess Tracker and Calorimeter or Tracker and ToF simultaneously! \n");
        printf(" If CaloLevel1 and ToF level0 remain unchanged: reprocess first tracker only and the CAL and/or TOF \n");
        printf(" If CaloLevel1 and ToF level0 could change: reprocess first CAL and/or TOF, then reprocess TRK only and finally reprocess CAL and/or TOF \n");
        printf(" IF you are crazy you can override this error using flag: --force-TRK  (i.e. DarthVader -v -b -idRun 0 -processFile myfile.root --force-TRK -ALL +TRK ) \n");
      }
      if ( !forcetrk ) throw -38;
    }

    //
    // Connect to the DB
    //
    if ( debug ) printf("\nConnecting to database... \n"); 
    //
    dbc = TSQLServer::Connect(host.Data(),user.Data(),psw.Data());
    if( !dbc ) throw -2;    
    //
    Bool_t connect = dbc->IsConnected();
    //
    if( !connect ) throw -2;    
    //
    if ( debug ) printf("...connected! \n\n");
    //
    glt = new GL_TABLES(host,user,psw);
    //GL_TABLES *glt = new GL_TABLES(host,user,psw);
    //
    printf("\n DB settings:\n SQL: %s Version: %s Host %s Port %i \n",dbc->GetDBMS(),dbc->ServerInfo(),dbc->GetHost(),dbc->GetPort());
    printf(" DB %s    ---   User %s \n\n",host.Data(),user.Data());
    if ( debug ) printf("\n DB INFORMATIONS:\n SQL: %s Version: %s Host %s Port %i \n\n",dbc->GetDBMS(),dbc->ServerInfo(),dbc->GetHost(),dbc->GetPort());
    //
    // Use UTC in the DB
    //
    stringstream myquery;
    myquery.str("");
    myquery << "SET time_zone='+0:00';";
    delete dbc->Query(myquery.str().c_str());
    myquery.str("");
    myquery << "SET wait_timeout=173000;";
    delete dbc->Query(myquery.str().c_str());
    delete dbc->Query("SET sql_mode = 'NO_UNSIGNED_SUBTRACTION';");
    //
    //
    // Create LEVEL2 filename and open it in update mode
    //
    if ( filename.IsNull() ){
      stringstream strun;
      strun.str("");
      strun << run;
      filename += outDir;
      filename += "/";
      filename += strun.str();
      filename += ".Level2.root";
    };
    //
    // check if file exists and check reprocess flag
    //
    if ( !reprocess ){
      if ( !gSystem->GetPathInfo(filename.Data(),NULL,(Long_t*)NULL,NULL,NULL) ) {
        if ( beverbose ) printf(" File %s already exists!\n",filename.Data());
        throw -37;
      }
    } 
    
    processFile = new TFile(filename.Data(),"UPDATE");
    if ( !processFile->IsOpen() ) throw -15;    
    //
    Long64_t maxsize = 10000000000LL;  
    TTree::SetMaxTreeSize(maxsize);
    processFile->SetCompressionLevel(1);
    //
    // ok, we are going to do some kinf of processing, the file is opened and ready. Save processing infos first
    //
    ProcInfo *procinfo = new ProcInfo();
    procinfo->runID = run;
    TTimeStamp *dt = new TTimeStamp();
    procinfo->date = dt->AsString();
    delete dt;
    for ( Int_t icl = 0; icl<numinp; icl++){
      procinfo->commandLine += Form("%s ",inps[icl]);
    }
    procinfo->outputFilename = filename;
    procinfo->localDir = gSystem->WorkingDirectory();
    procinfo->uname = gSystem->GetFromPipe("uname -a");
    procinfo->DB = host;

    TTree *pinfo = 0;
    pinfo = (TTree*)processFile->Get("ProcessingInfo");
    // ProcessingInfo tree does not exist, crating proc info
    if ( !pinfo ){
      if ( debug ) printf("ProcessingInfo tree does not exist, crating proc info\n");
      pinfo = new TTree("ProcessingInfo","Log of data processing");
      pinfo->Branch("ProcInfo","ProcInfo",&procinfo);
    } else {
      pinfo->SetBranchAddress("ProcInfo",&procinfo);
    }
    pinfo->Fill();
    processFile->cd();
    pinfo->Write("ProcessingInfo",TObject::kOverwrite);
    if ( procinfo ) delete procinfo;
    if ( pinfo ) pinfo->Delete();    
    //
    // Run the core program, put any output error in the "error" variable
    //
    if ( debug ) printf("\n\n Pre-processing:\n\n");
    //
    timer.Start(kTRUE);
    if ( RUN ) {
      glt->ResetCounters();
      if ( debug ) printf(" Retrieve, if the case, the RUN informations from the DB...\n");
      printf(" RunInfo called\n");
      if ( debug ) printf("                      >>>>>>>>>>>>>>>>>>>| start RunInfoCore STDOUT |<<<<<<<<<<<<<<<<<<<\n");
      RUNSGN = RunInfoCore(run,processFile,dbc,version,runargc,runargv);
      if ( debug ) printf("                      >>>>>>>>>>>>>>>>>>>|  end RunInfoCore STDOUT  |<<<<<<<<<<<<<<<<<<<\n");
      if ( debug ) printf(" ...done\n");
      NQRUN = glt->GetNqueries();
    };
    timer.Stop();
    runtime = timer.RealTime();
    cruntime = timer.CpuTime();
    //
    // From the Run Infos extract acq_var_info to determine if detectors are in the acquisition or not
    //
    if ( debug ) printf(" Checking if requested detectors are in the acquisition\n");
    ItoRunInfo *runinfo = new ItoRunInfo(processFile);
    Int_t sgnl = runinfo->Read(run);
    if ( sgnl != 0 ) throw -17;
    nevents = runinfo->GetEntries();
    if ( run == 0 ) nevents = runinfo->GetFileEntries();
    nruns = runinfo->GetNoRun();
    if ( debug ) printf(" => ACQ_VAR_INFO = %i \n",runinfo->ACQ_VAR_INFO);
    if ( TRK && !(runinfo->ACQ_VAR_INFO & (1 << 4)) ){
      DVSGN += 1;
      if ( tedious ) throw -30;
      if ( autom ){
	TRK = 0;
	if ( debug ) printf(" TRK excluded from processing \n");
      };
      if ( zerofill && debug ) printf(" TRK is not in the acquisition! \n");
    };
    if ( TOF && !(runinfo->ACQ_VAR_INFO & (1 << 0)) ){
      DVSGN += 2;
      if ( tedious ) throw -31;
      if ( autom ){
	TOF = 0;
	if ( debug ) printf(" TOF excluded from processing \n");
      };      
      if ( zerofill && debug ) printf(" TOF is not in the acquisition! \n");
    };
    if ( CAL && !(runinfo->ACQ_VAR_INFO & (1 << 3)) ){
      DVSGN += 4;
      if ( tedious ) throw -32;
      if ( autom ){
	CAL = 0;
	if ( debug ) printf(" CAL excluded from processing \n");
      };
      if ( zerofill && debug ) printf(" CAL is not in the acquisition! \n");
    };
    if ( AC  && (!(runinfo->ACQ_VAR_INFO & (1 << 1)) || !(runinfo->ACQ_VAR_INFO & (1 << 2))) ){
      DVSGN += 8;
      if ( tedious ) throw -33;
      if ( autom ){
	AC = 0;
	if ( debug ) printf(" AC excluded from processing \n");
      };
      if ( zerofill && debug ) printf(" AC is not in the acquisition! \n");
    };
    if ( S4  && !(runinfo->ACQ_VAR_INFO & (1 << 5)) ){
      DVSGN += 16;
      if ( tedious ) throw -34;
      if ( autom ){
	S4 = 0;
	if ( debug ) printf(" S4 excluded from processing \n");
      };
      if ( zerofill && debug ) printf(" S4 is not in the acquisition! \n");
    };
    if ( ND  && !(runinfo->ACQ_VAR_INFO & (1 << 9)) ){
      DVSGN += 32;
      if ( tedious ) throw -35;
      if ( autom ){
	ND = 0;
	if ( debug ) printf(" ND excluded from processing \n");
      };
      if ( zerofill && debug ) printf(" ND is not in the acquisition! \n");
    };
    //
    if ( !DVSGN ){
      if ( debug ) printf(" OK! Start processing detector's data. \n");
    } else {
      if ( debug ) printf(" WARNING! missing detector(s)! Start anyway processing detector's data. \n");
    };
    if ( debug ) printf("\n End pre-processing \n\n");
    //
    dbc->Close();
    //
    //
    timer.Start(kTRUE);
    if ( TRG ) {
      glt->ResetCounters();
      printf(" TriggerLevel2 called\n");
      if ( debug ) printf("                      >>>>>>>>>>>>>>>>>>>| start TrigCore STDOUT |<<<<<<<<<<<<<<<<<<<\n");
      TRGSGN = TrigCore(run,processFile,glt,trgargc,trgargv);
      if ( debug ) printf("                      >>>>>>>>>>>>>>>>>>>|  end TrigCore STDOUT  |<<<<<<<<<<<<<<<<<<<\n");
      NQTRG = glt->GetNqueries();
    };
    timer.Stop();
    trgtime = timer.RealTime();
    ctrgtime = timer.CpuTime();
    //
    //
    // new fitting algorithm require calorimeter level1 and tof XXX to be processed first
    //
    if ( newfit ) {
      timer.Start(kTRUE);
      if ( TOF && TRK ) {
        glt->ResetCounters();
        printf(" ToFLevel2 called, 1st call\n");
        if ( debug ) printf("                      >>>>>>>>>>>>>>>>>>>| start ToFCore STDOUT |<<<<<<<<<<<<<<<<<<<\n");
        string tstring = "--level1-only";
        tofargv[tofargc] = (char *)tstring.c_str();
        tofargc++;
        TOFSGN1 = ToFCore(run,processFile,glt,tofargc,tofargv);
        if ( debug ) printf("                      >>>>>>>>>>>>>>>>>>>|  end ToFCore STDOUT  |<<<<<<<<<<<<<<<<<<<\n");
        NQTOF1 = glt->GetNqueries();
      };
      timer.Stop();
      toftime1 = timer.RealTime();
      ctoftime1 = timer.CpuTime();
      //
      timer.Start(kTRUE);
      if ( CAL && TRK ) {
        glt->ResetCounters();
        printf(" CalorimeterLevel2 called, 1st call\n");
        if ( debug ) printf("                      >>>>>>>>>>>>>>>>>>>| start CaloCore STDOUT |<<<<<<<<<<<<<<<<<<<\n");
        string cstring = "--level1-only";
        calargv[calargc] = (char *)cstring.c_str();
        calargc++;
        CALSGN1 = CaloCore(run,processFile,glt,calargc,calargv);
        if ( debug ) printf("                      >>>>>>>>>>>>>>>>>>>|  end CaloCore STDOUT  |<<<<<<<<<<<<<<<<<<<\n");
        NQCAL1 = glt->GetNqueries();
      };
      timer.Stop();
      caltime1 = timer.RealTime();
      ccaltime1 = timer.CpuTime();    
    }
    //
    //
    timer.Start(kTRUE);
    if ( TRK ) {
      glt->ResetCounters();
      printf(" TrackerLevel2 called\n");                
      if ( debug ) printf("                      >>>>>>>>>>>>>>>>>>>| start TrkCore STDOUT |<<<<<<<<<<<<<<<<<<<\n");
      TRKSGN = TrkCore(run,processFile,glt,trkargc,trkargv);
      gSystem->Unlink("TrackerFolder"); //patch
      if ( debug ) printf("                      >>>>>>>>>>>>>>>>>>>|  end TrkCore STDOUT  |<<<<<<<<<<<<<<<<<<<\n");
      NQTRK = glt->GetNqueries();
    };
    timer.Stop();
    trktime = timer.RealTime();
    ctrktime = timer.CpuTime();
    //
    timer.Start(kTRUE);
    if ( TOF ) {
      glt->ResetCounters();
      printf(" ToFLevel2 called\n");
      if ( debug ) printf("                      >>>>>>>>>>>>>>>>>>>| start ToFCore STDOUT |<<<<<<<<<<<<<<<<<<<\n");
      if ( !reprocess ){
        string tstring = "--delete-tree";
        tofargv[tofargc] = (char *)tstring.c_str();
      } else {
        if ( TRK ) tofargc--;
      }
      TOFSGN = ToFCore(run,processFile,glt,tofargc,tofargv);
      if ( debug ) printf("                      >>>>>>>>>>>>>>>>>>>|  end ToFCore STDOUT  |<<<<<<<<<<<<<<<<<<<\n");
      NQTOF = glt->GetNqueries();
    };
    timer.Stop();
    toftime = timer.RealTime();
    ctoftime = timer.CpuTime();
    //
    timer.Start(kTRUE);
    if ( CAL ) {
      glt->ResetCounters();
      printf(" CalorimeterLevel2 called\n");
      if ( debug ) printf("                      >>>>>>>>>>>>>>>>>>>| start CaloCore STDOUT |<<<<<<<<<<<<<<<<<<<\n");
      if ( !reprocess ){
        string cstring = "--delete-calo-tree";
        calargv[calargc] = (char *)cstring.c_str();
      } else {
        if ( TRK ) calargc--;
      }
      CALSGN = CaloCore(run,processFile,glt,calargc,calargv);
      if ( debug ) printf("                      >>>>>>>>>>>>>>>>>>>|  end CaloCore STDOUT  |<<<<<<<<<<<<<<<<<<<\n");
      NQCAL = glt->GetNqueries();
    };
    timer.Stop();
    caltime = timer.RealTime();
    ccaltime = timer.CpuTime();
    //
    timer.Start(kTRUE);
    if ( AC ) {
      glt->ResetCounters();
      printf(" AnticounterLevel2 called\n");
      if ( debug ) printf("                      >>>>>>>>>>>>>>>>>>>| start AcCore STDOUT |<<<<<<<<<<<<<<<<<<<\n");
      ACSGN = AcCore(run,processFile,glt,acargc,acargv);
      if ( debug ) printf("                      >>>>>>>>>>>>>>>>>>>|  end AcCore STDOUT  |<<<<<<<<<<<<<<<<<<<\n");
      NQAC = glt->GetNqueries();
    };
    timer.Stop();
    actime = timer.RealTime();
    cactime = timer.CpuTime();
    //
    timer.Start(kTRUE);
    if ( S4 ) {
      glt->ResetCounters();
      printf(" S4Level2 called\n");
      if ( debug ) printf("                      >>>>>>>>>>>>>>>>>>>| start S4Core STDOUT  |<<<<<<<<<<<<<<<<<<<\n");
      S4SGN = S4Core(run,processFile,glt,s4argc,s4argv);
      if ( debug ) printf("                      >>>>>>>>>>>>>>>>>>>|  end S4Core STDOUT   |<<<<<<<<<<<<<<<<<<<\n");
      NQS4 = glt->GetNqueries();
    };
    timer.Stop();
    s4time = timer.RealTime();
    cs4time = timer.CpuTime();
    //
    timer.Start(kTRUE);
    if ( ND ) {
      glt->ResetCounters();
      printf(" NDLevel2 called\n");
      if ( debug ) printf("                      >>>>>>>>>>>>>>>>>>>| start NDCore STDOUT  |<<<<<<<<<<<<<<<<<<<\n");
      NDSGN = NDCore(run,processFile,glt,ndargc,ndargv);
      if ( debug ) printf("                      >>>>>>>>>>>>>>>>>>>|  end NDCore STDOUT   |<<<<<<<<<<<<<<<<<<<\n");
      NQND = glt->GetNqueries();
    };
    timer.Stop();
    ndtime = timer.RealTime();
    cndtime = timer.CpuTime();
    //
    timer.Start(kTRUE);
    if ( ORB ) {
      glt->ResetCounters();
      printf(" OrbitalInfo called\n");
      if ( debug ) printf("                      >>>>>>>>>>>>>>>>>>>| start OrbitalInfoCore STDOUT  |<<<<<<<<<<<<<<<<<<<\n");
      ORBSGN = OrbitalInfoCore(run,processFile,glt,orbargc,orbargv);
      if ( debug ) printf("                      >>>>>>>>>>>>>>>>>>>|  end OrbitalInfoCore STDOUT   |<<<<<<<<<<<<<<<<<<<\n");
      NQORB = glt->GetNqueries();
    };    
    timer.Stop();
    orbtime = timer.RealTime();
    corbtime = timer.CpuTime();
    //
    NQTOT = 2 + NQRUN + NQTRK + NQCAL + NQND + NQS4 + NQAC + NQTRG + NQTOF + NQORB + NQCAL1 + NQTOF1; 
    //
    delete glt;
    delete runinfo;
    //
  } catch(Int_t signal) {    
    error = signal;
    switch(signal){
    case 51:   message += " GLTABLES - TO_TIME < time when querying tables"; break;
    case -1:   message += " Missing/wrong run ID input parameter"; break;
    case -2:   message += " DB connection failure"; break;
    case -3:   message += " Error in input parameters (check format)"; break;
    case -4:   message += " Request reprocessing of all runs (idRun = 0) but processFile is missing"; break;
    case -5:   message += " RUNINFO - ERROR: no run with this ID_RUN (ID_RUN mismatch?) "; break;
    case -6:   message += " No LEVEL0 file "; break;
    case -7:   message += " No Physics tree in LEVEL0 file"; break;
    case -8:   message += " No Header branch in LEVEL0 Physics tree"; break;
    case -9:   message += " No Registry branch in LEVEL0 Physics tree"; break;
    case -11:  message += " LEVEL0 Physics tree is empty"; break;
    case -12:  message += " Too few entries in the tree"; break;
    case -13:  message += " Cannot create processFolder directory"; break;
    case -14:  message += " Error querying the DB"; break;
    case -15:  message += " Cannot open file for writing"; break;
    case -17:  message += " Error during pre-processing"; break;
    case -22:  message += " Unknown input or wrong syntax in input paramters!"; break;
    case -30:  message += " No TRK in the acquisition"; break;
    case -31:  message += " No TOF in the acquisition"; break;
    case -32:  message += " No CAL in the acquisition"; break;
    case -33:  message += " No AC in the acquisition"; break;
    case -34:  message += " No S4 in the acquisition"; break;
    case -35:  message += " No ND in the acquisition"; break;
    case -36:  message += " I/O error or missing entry"; break;
    case -37:  message += " Cannot override output file, see help and use -r option"; break;
    case -38:  message += " Cannot process TRK and CAL or TOF simultaneously"; break;
   
      //
    case -50:  message += " GLTABLES - No entries matching GL_RUN query"; break;
    case -51:  message += " GLTABLES - No entries matching GL_ROOT query"; break;
    case -52:  message += " GLTABLES - No entries matching GL_PARAM query"; break;
    case -53:  message += " GLTABLES - No entries matching GL_TRK_CALIB query"; break;
    case -54:  message += " GLTABLES - No entries matching GL_CALO_CALIB query"; break;
    case -55:  message += " GLTABLES - No entries matching GL_S4_CALIB query"; break;
    case -56:  message += " GLTABLES - No entries matching GL_TLE query"; break;
    case -57:  message += " GLTABLES - DB connection gone and not able to reconnect"; break;
      //      
    case -100: message += " CALORIMETERLEVEL2 - No Level2 input file"; break;
    case -101: message += " CALORIMETERLEVEL2 -  Cannot open Level2 file"; break;
    case -102: message += " CALORIMETERLEVEL2 -  No Tracker TTree in Level2 file"; break;
    case -103: message += " CALORIMETERLEVEL2 -  No Calorimeter TBranch in Level0 file"; break;
    case -104: message += " CALORIMETERLEVEL2 -  No Trigger TTree in Level0 file"; break;
    case -105: message += " CALORIMETERLEVEL2 -  No Calorimeter ADC2MIP conversion file"; break;
    case -106: message += " CALORIMETERLEVEL2 -  No Calorimeter alignement file"; break;
    case -107: message += " CALORIMETERLEVEL2 -  Cannot find Level0 file needed for the calibration"; break;
    case -108: message += " CALORIMETERLEVEL2 -  Cannot open Level0 file needed for the calibration"; break;
    case -109: message += " CALORIMETERLEVEL2 -  No CalibCalPed TTree in Level0 file needed for the calibration"; break;
    case -110: message += " CALORIMETERLEVEL2 -  No calibrations in Level0 file needed for the calibration"; break;
    case -111: message += " CALORIMETERLEVEL2 -  Corrupted calibration"; break;
    case -112: message += " CALORIMETERLEVEL2 -  No physics event related to registry entry in Level0 file"; break;
    case -113: message += " CALORIMETERLEVEL2 -  No tracker event related to registry entry in Level2 file"; break;
    case -114: message += " CALORIMETERLEVEL2 -  Help called"; break; 
    case -115: message += " CALORIMETERLEVEL2 -  No Calorimeter bad strip offline mask file"; break;
    case -116: message += " CALORIMETERLEVEL2 -  DB connection problems"; break;
    case -117: message += " CALORIMETERLEVEL2 -  Cannot reprocess file with Level1 data without calling Level1 routine"; break;
    case -118: message += " CALORIMETERLEVEL2 -  Cannot reprocess file without Level1 data calling Level1 routine"; break;
    case -119: message += " CALORIMETERLEVEL2 -  No CalibCalPulse2 TTree in Level0 file needed for the calibration"; break;
    case -120: message += " CALORIMETERLEVEL2 -  No CalibCalPulse1 TTree in Level0 file needed for the calibration"; break;
    case -121: message += " CALORIMETERLEVEL2 -  Cannot open calorimeter neighbour crosstalk correction table file"; break;
    case -122: message += " CALORIMETERLEVEL2 -  Cannot open calorimeter second neighbour crosstalk correction table file"; break;
    case -123: message += " CALORIMETERLEVEL2 -  Cannot open calorimeter special calibration file"; break;
    case -124: message += " CALORIMETERLEVEL2 -  Cannot open calorimeter max rms file"; break;
    case -125: message += " CALORIMETERLEVEL2 -  Cannot open calorimeter silicon crosstalk correction table file"; break;
      //
    case -200: message += " TRACKERLEVEL2 - LEVEL1 framework unknown (HBOOK/ROOT)"; break;
    case -201: message += " TRACKERLEVEL2 - LEVEL2 framework unknown (HBOOK/ROOT)"; break;
    case -202: message += " TRACKERLEVEL2 - Neither LEVEL1 nor LEVEL2 output requested"; break;
    case -203: message += " TRACKERLEVEL2 - No Tracker branch in LEVEL0 Physics tree"; break;
    case -204: message += " TRACKERLEVEL2 - No reprocessing implemented for LEVEL1 output"; break;
    case -205: message += " TRACKERLEVEL2 - Error accessing RunInfo "; break;
    case -206: message += " TRACKERLEVEL2 - Extended-tracking mode - no Calorimeter and/or ToF trees found"; break;
    case -210: message += " TRACKERLEVEL2 - Error opening/reading trk mask GL_PARAM parameters "; break;
    case -211: message += " TRACKERLEVEL2 - Error opening/reading trk alignment GL_PARAM parameters"; break;
    case -212: message += " TRACKERLEVEL2 - Error opening/reading trk mip GL_PARAM parameters"; break;
    case -213: message += " TRACKERLEVEL2 - Error opening/reading trk charge GL_PARAM parameters"; break;
    case -214: message += " TRACKERLEVEL2 - Error opening/reading trk pfa GL_PARAM parameters"; break;
    case -215: message += " TRACKERLEVEL2 - Error opening/reading field GL_PARAM parameters"; break;
    case -216: message += " TRACKERLEVEL2 - Error opening/reading default calibration GL_PARAM parameters"; break;
    case -298: message += " TRACKERLEVEL2 - Reprocessing not implemented in standalone mode"; break;
    case -299: message += " TRACKERLEVEL2 - Not yet implemented"; break;
      //
    case -300: message += " TOFLEVEL2 - No Trigger branch in Level0 tree"; break;
    case -301: message += " TOFLEVEL2 - Cannot open file for writing"; break;
    case -302: message += " TOFLEVEL2 - No tracker tree in Level2 file"; break;
    case -303: message += " TOFLEVEL2 - No Tof branch in Level0 file"; break;
    case -304: message += " TOFLEVEL2 - No trigger tree in Level2 file"; break;
    case -313: message += " TOFLEVEL2 - No more tracker events in Level2 file"; break;
    case -314: message += " TOFLEVEL2 - DB connection problems"; break; 
    case -315: message += " TOFLEVEL2 - Problems with dE/dx II order correction file parameter"; break; 
    case -316: message += " TOFLEVEL2 - Problems with dE/dx II order correction, dividing by zero!"; break; 
    case -317: message += " TOFLEVEL2 - Problems with dE/dx II order correction, outside time limits!"; break; 
    case -318: message += " TOFLEVEL2 - Problems with dE/dx II order correction, too many time intervals!"; break; 
    case -319: message += " TOFLEVEL2 - No more trigger events in Level2 file"; break;
      //
    case -401: message += " TRIGGERLEVEL2 - Cannot open file for writing"; break;
    case -402: message += " TRIGGERLEVEL2 - No Trigger branch in Level0 tree"; break;
    case -403: message += " TRIGGERLEVEL2 - DB connection problems"; break; 
      //
    case -500: message += " S4LEVEL2 - No level2 file"; break;
    case -501: message += " S4LEVEL2 - Cannot open file for writing"; break;
    case -502: message += " S4LEVEL2 - No result from GL_S4_CALIB"; break;
    case -503: message += " S4LEVEL2 - No S4 branch in Level0 tree"; break;
    case -504: message += " S4LEVEL2 - DB connection problems"; break; 
      //
    case -600: message += " NDLEVEL2 - No level2 file"; break;
    case -601: message += " NDLEVEL2 - Cannot open file for writing"; break;
    case -603: message += " NDLEVEL2 - No S4Level2 branch in Level0 tree"; break;
    case -604: message += " NDLEVEL2 - DB connection problems"; break; 
      //
    case -701: message += " ACLEVEL2 - Cannot open file for writing"; break;
    case -704: message += " ACLEVEL2 - No Anticounter branch in Level0 tree"; break;
    case -705: message += " ACLEVEL2 - DB connection problems"; break; 
      //
    case -800: message += " RUNINFO - No such run in the RunInfo list"; break;
    case -801: message += " RUNINFO - No RunInfo tree in Level2 file"; break;
    case -802: message += " RUNINFO - Cannot open file for writing"; break;
    case -803: message += " RUNINFO - Updating but no RunInfo tree in Level2 file"; break;
    case -804: message += " RUNINFO - Unknown detector"; break;
    case -805: message += " RUNINFO - Reprocessing data but no RunInfo tree in Level2 file"; break;
    case -806: message += " RUNINFO - Can not handle more than 500 runs"; break;
    case -807: message += " RUNINFO - DB connection problems"; break;
      //
    case -900: message += " OrbitalInfo - no ToF tree"; break;
    case -901: message += " OrbitalInfo - Mismatch between tracker and tof tree branches concerning extended tracking algorithm(s)"; break;
     //
    default: message += "Unidentified error or warning"; break;
    };
    printf("\n");
    if ( signal < 0 ) cout << " ERROR ("<< signal << ") "<< message <<endl;
  }
  //
  // Warnings from XCore routines and from DV:
  //
  if ( debug && DVSGN ) printf(" DVSGN = %i \n",DVSGN);
  if ( DVSGN ) printf("\n WARNING DarthVader: \n"); 
  if ( DVSGN & (1 << 0) ) printf(" - No tracker in the acquisition\n");
  if ( DVSGN & (1 << 1) ) printf(" - No ToF in the acquisition\n"); 
  if ( DVSGN & (1 << 2) ) printf(" - No calorimeter in the acquisition\n"); 
  if ( DVSGN & (1 << 3) ) printf(" - No anticounters in the acquisition\n");
  if ( DVSGN & (1 << 4) ) printf(" - No S4 in the acquisition\n"); 
  if ( DVSGN & (1 << 5) ) printf(" - No neutron detector in the acquisition\n"); 
  //
  // CaloCore, first call:
  //
  switch(CALSGN1){
  case 100: printf("\n WARNING CALORIMETER - Data with no associated calibration\n");
  case 101: printf("\n WARNING CALORIMETER - No tracks or good events in this run\n");
  }
  //
  // CaloCore:
  //
  switch(CALSGN){
  case 100: printf("\n WARNING CALORIMETER - Data with no associated calibration\n");
  case 101: printf("\n WARNING CALORIMETER - No tracks or good events in this run\n");
  };
  //
  // OrbitalInfoCore:
  //
  switch(ORBSGN){
  case 900: printf("\n WARNING ORBITALINFO - No inclination MCMDs\n");
  };
  //
  // no other at the moment
  //
  //
  // Close the DB connection
  //
  if ( dbc ){
    if ( debug ) printf("\nClose the connection to the database... \n");
    dbc->Close();
    if ( debug ) printf("...connection terminated!\n\n");   
  };
  if ( processFile ){
    processFile->cd();
    processFile->WriteStreamerInfo();
    if ( debug ) processFile->ls();
    processFile->Close();
  };
  //
  // print benchmark results (if the case)
  //
  dvtimer.Stop();
  dvtime = dvtimer.RealTime();
  cdvtime = dvtimer.CpuTime();
  if ( bench ){
    Float_t runrt = 0.;
    Float_t trkrt = 0.;
    Float_t calrt = 0.;
    Float_t tofrt = 0.;
    Float_t calrt1 = 0.;
    Float_t tofrt1 = 0.;
    Float_t trgrt = 0.;
    Float_t acrt = 0.;
    Float_t s4rt = 0.;
    Float_t ndrt = 0.;
    Float_t orbrt = 0.;
    Float_t dvrt = (nevents+1)/dvtime;
    if ( RUN ) runrt = nruns/runtime;
    if ( TRK ) trkrt = (nevents+1)/trktime;
    if ( CAL ) calrt = (nevents+1)/caltime;
    if ( TOF && TRK && newfit ) tofrt1 = (nevents+1)/toftime1;
    if ( CAL && TRK && newfit ) calrt1 = (nevents+1)/caltime1;
    if ( TOF ) tofrt = (nevents+1)/toftime;
    if ( TRG ) trgrt = (nevents+1)/trgtime;
    if ( AC ) acrt = (nevents+1)/actime;
    if ( S4 ) s4rt = (nevents+1)/s4time;
    if ( ND ) ndrt = (nevents+1)/ndtime;
    if ( ORB ) orbrt = (nevents+1)/orbtime;
    //
    printf("\n\n###########################################################################################\n");
    printf("#              Benchmark results:      nevents = %10u     runs = %3u                #\n",(nevents+1),nruns);
    printf("###########################################################################################\n");
    printf("# Detector # Core routine called # Queries  #     Real Time   #   CPU time   #  Events/s  #\n");
    printf("###########################################################################################\n");
    printf("# RUN      #         %i           #   %3u    #      %8.2f   #    %8.2f  #  %8.2f  #\n",RUN,NQRUN,fabs(runtime),fabs(cruntime),runrt);
    printf("# TRG      #         %i           #   %3u    #      %8.2f   #    %8.2f  #  %8.2f  #\n",TRG,NQTRG,fabs(trgtime),fabs(ctrgtime),trgrt);
    if ( newfit ){
    printf("# TOF L1   #         %i           #   %3u    #      %8.2f   #    %8.2f  #  %8.2f  #\n",(TOF&&TRK),NQTOF1,fabs(toftime1),fabs(ctoftime1),tofrt1);    
    printf("# CAL L1   #         %i           #   %3u    #      %8.2f   #    %8.2f  #  %8.2f  #\n",CAL,NQCAL1,fabs(caltime1),fabs(ccaltime1),calrt1);
    }
    printf("# TRK      #         %i           #   %3u    #      %8.2f   #    %8.2f  #  %8.2f  #\n",TRK,NQTRK,fabs(trktime),fabs(ctrktime),trkrt);
    printf("# TOF      #         %i           #   %3u    #      %8.2f   #    %8.2f  #  %8.2f  #\n",TOF,NQTOF,fabs(toftime),fabs(ctoftime),tofrt);
    printf("# CAL      #         %i           #   %3u    #      %8.2f   #    %8.2f  #  %8.2f  #\n",CAL,NQCAL,fabs(caltime),fabs(ccaltime),calrt);
    printf("# AC       #         %i           #   %3u    #      %8.2f   #    %8.2f  #  %8.2f  #\n",AC,NQAC,fabs(actime),fabs(cactime),acrt);
    printf("# S4       #         %i           #   %3u    #      %8.2f   #    %8.2f  #  %8.2f  #\n",S4,NQS4,fabs(s4time),fabs(cs4time),s4rt);
    printf("# ND       #         %i           #   %3u    #      %8.2f   #    %8.2f  #  %8.2f  #\n",ND,NQND,fabs(ndtime),fabs(cndtime),ndrt);
    printf("# ORB      #         %i           #   %3u    #      %8.2f   #    %8.2f  #  %8.2f  #\n",ORB,NQORB,fabs(orbtime),fabs(corbtime),orbrt);
    printf("###########################################################################################\n");
    printf("# Total    #                     #  %4u    #      %8.2f   #    %8.2f  #  %8.2f  #\n",NQTOT,fabs(dvtime),fabs(cdvtime),dvrt);
    printf("###########################################################################################\n");
  };
  //
  //
  if ( error != 0 ) printf("\n\n WARNING: exiting with signal %i \n\n",error);
  //
  //
  //
  if ( remfile && error < 0 ){
    printf(" -c or --clean option used, deleting file %s \n\n",filename.Data());
    gSystem->Unlink(filename.Data()); 
  };
  //
  if ( !error && (CALSGN1 || TOFSGN1 || CALSGN || TRKSGN || TRGSGN || TOFSGN || RUNSGN || ORBSGN || ACSGN || S4SGN || NDSGN || DVSGN) ) error = 1;
  //
  printf("\n Finished, exiting...\n\n");
  //
  // Close redirection if the case.
  //
  if ( !beverbose ) close(nul);
  //
  //
  if ( !error ) exit(0);       // no errors
  if ( error == 1 ) exit(255);  // warnings
  exit(1);                     // errors
}
