//
// Given a calibration and a data file this program create an ntuple with LEVEL2 S4 variables 
//
//
// C/C++ headers
//
#include <fstream>
#include <string.h>
#include <iostream>
#include <cstring>
#include <stdio.h>
//
// ROOT headers
//
#include <TGraph.h>
#include <TF1.h>
#include <TTree.h>
#include <TClassEdit.h>
#include <TObject.h>
#include <TList.h>
#include <TArrayI.h>
#include <TArrayD.h>
#include <TSystem.h>
#include <TSystemDirectory.h>
#include <TString.h>
#include <TFile.h>
#include <TClass.h>
#include <TSQLServer.h>
#include <TSQLRow.h>
#include <TSQLResult.h>
#include <TClonesArray.h>
#include <stdlib.h>
#include <math.h>
//
// RunInfo header
//
#include <RunInfo.h>
#include <GLTables.h>
//
// YODA headers
//
#include <PamelaRun.h>
#include <PscuHeader.h>
#include <PscuEvent.h>
#include <EventHeader.h>
#include <CalibS4Event.h>
#include <physics/S4/S4Event.h>
//
// This program headers
//
#include <S4Level2.h>
#include <S4Core.h>
#include <S4Verl2.h>
//
using namespace std;
//
/*
 * Fit function Received from Valeria Malvezzi 06/02/2006
 */
Double_t fitf(Double_t *x, Double_t *par){  
  Double_t fitval =(par[0]*x[0])+par[1];
  return fitval;
}

/*
 * Fit the S4 calibration with a straight line - Received from Valeria Malvezzi 06/02/2006
 */
TArrayD *S4_paramfit(UInt_t atime, TSQLServer *dbc){      
  //  
  TArrayD *parametri = new TArrayD(2);
  //
  GL_S4_CALIB *glS4calib = new GL_S4_CALIB();
  //
  //  if ( !dbc->IsConnected() ) throw -504;
  Int_t s4sig = glS4calib->Query_GL_S4_CALIB(atime, dbc);
  if ( s4sig != -57 && s4sig < 0 ){
    parametri->AddAt(0.,0);
    parametri->AddAt(0.,1); 
    return parametri;
  };
  if ( s4sig < 0 ) throw s4sig;
  //
  GL_ROOT *glroot = new GL_ROOT();
  //  if ( !dbc->IsConnected() ) throw -504;
  glroot->Query_GL_ROOT(glS4calib->ID_ROOT_L0,dbc);
  //
  stringstream ftmpname;
  ftmpname.str("");
  ftmpname << glroot->PATH.Data() << "/";
  ftmpname << glroot->NAME.Data();
  //
  TFile *file = 0;
  file = new TFile(ftmpname.str().c_str());
  //
  if ( !file ) return(NULL);
  //
  TTree *tr = 0;
  tr = (TTree*)file->Get("CalibS4");
  if ( !tr ){
    file->Close();
    return(NULL);
  };
  //
  pamela::CalibS4Event *S4CalibEvent = 0;
  tr->SetBranchAddress("CalibS4", &S4CalibEvent);
  if ( tr->GetEntries() < glS4calib->EV_ROOT ) return(NULL);
  //
  tr->GetEntry(glS4calib->EV_ROOT);
  //
  // Variables initialization 
  //
  Double_t mip[3]={1, 30, 300};
  Double_t adc[3] = {0.,0.,0.};
  //
  // Fit calibrations and find parameters to calibrate data 
  //
  pamela::S4::S4Event  *s4Record = 0; 
  //
  for (Int_t j = 0; j < 4; j++){
    for (Int_t i = 0; i < 128; i++){
      s4Record = (pamela::S4::S4Event*)S4CalibEvent->Records->At((j*128 + i));
      switch (j) {
      case 0 :{
	adc[0]=adc[0]+((s4Record->S4_DATA)-32);
	break;
      };
      case 1 :{
	adc[1]=adc[1]+((s4Record->S4_DATA)-32);
	break;
      };
      case 3 :{
	adc[2]=adc[2]+((s4Record->S4_DATA)-32);
	break;
      };
      };
    };
  };
  //
  adc[0]=adc[0]/128;
  adc[1]=adc[1]/128;
  adc[2]=adc[2]/128;  
  //  if ( IsDebug() ) printf(" adc1 = %g adc2 = %g adc3 = %g\n",adc[0],adc[1],adc[2]);
  TGraph *fitpar = new TGraph (3, adc, mip);
  TF1 *func = new TF1("fitf", fitf, -1., 400., 2); // function definition with 2 parameters
  //  
  func->SetParameters(0.3,1.); // parameters initialization to 1
  func->SetParNames("m","q"); //parameter's name 
  fitpar->Fit(func,"qr"); //function fit 
  parametri->AddAt(func->GetParameter(0),0);
  parametri->AddAt(func->GetParameter(1),1); 
  //  if ( parametri[0] < 0. || parametri[0] > 0.5 || parametri[1] < 0.7 || parametri[1] > 1.1 ) valid = 0;
  //
  delete glroot;
  delete glS4calib;
  delete fitpar;
  delete func;
  file->Close();
  // 
  return parametri;
};

//
// CORE ROUTINE
//
//
int S4Core(UInt_t run, TFile *file,GL_TABLES *glt, Int_t S4argc, char *S4argv[]){
  //
  // Set these to true to have a verbose output.
  //
  Bool_t debug = false;
  Bool_t verbose = false;
  //    
  // 
  // Output directory is the working directoy.
  //
  const char* outDir = gSystem->DirName(gSystem->DirName(file->GetPath()));
  //
  Int_t i = 0;
  TString processFolder = Form("S4Folder_%u",run);
  if ( S4argc > 0 ){
    i = 0;
    while ( i < S4argc ){
      if ( !strcmp(S4argv[i],"-processFolder") ) {
	if ( S4argc < i+1 ){
	  throw -3;
	};
	processFolder = (TString)S4argv[i+1];
	i++;
      };
      if ( (!strcmp(S4argv[i],"--debug")) || (!strcmp(S4argv[i],"-g"))) {
	verbose = true;
	debug = true;
      };
      if ( (!strcmp(S4argv[i],"--verbose")) || (!strcmp(S4argv[i],"-v"))) {
	verbose = true;
      };
      i++;
    };
  };
  // Variables for level2 
  //
  TTree *S4tr = 0;
  UInt_t nevents = 0;
  //
  // Variables needed to reprocess data
  //
  Long64_t maxsize = 10000000000LL;  
  TTree::SetMaxTreeSize(maxsize);
  //
  TString S4version;
  ItoRunInfo *runinfo = 0;
  TArrayI *runlist = 0;
  TTree *S4trclone = 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;
  Double_t  ParamFit0 =  0.; 
  Double_t  ParamFit1 =  0.; 
  //
  // variables needed to handle error signals
  //
  Int_t code = 0;
  Int_t sgnl;
  //
  // S4 level2 classes
  //
  S4Level2 *s4 = new S4Level2();
  S4Level2 *s4clone = new S4Level2();
  //
  // define variables for opening and reading level0 file
  //
  TFile *l0File = 0;
  TTree *l0tr = 0;
  TBranch *l0head = 0;
  TBranch *l0S4 =0;
  pamela::S4::S4Event  *l0s4e = 0;
  pamela::EventHeader *eh = 0;
  pamela::PscuHeader *ph = 0;
  //
  // Define other basic variables
  // 
  UInt_t procev = 0;
  stringstream file2;
  stringstream file3;
  stringstream qy;
  Int_t totevent = 0;
  UInt_t atime = 0;
  //  Int_t ei = 0; 
  UInt_t re = 0;
  //
  // Working filename
  //
  TString outputfile;
  stringstream name;
  name.str("");
  name << outDir << "/";
  //
  // temporary file and folder
  //
  TFile *tempfile = 0;
  TTree *tempS4 = 0;
  stringstream tempname;
  stringstream S4folder;
  Bool_t myfold = false;
  tempname.str("");
  tempname << outDir;
  tempname << "/" << processFolder.Data();
  S4folder.str("");
  S4folder << tempname.str().c_str();
  tempname << "/S4tree_run";
  tempname << run << ".root";  
  //
  // DB classes
  //
  GL_ROOT *glroot = new GL_ROOT();
  GL_TIMESYNC *dbtime = 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 MyDetector2 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() ){
    //printf(" S4 - ERROR: cannot open file for writing\n");
    throw -501;    
  };
  //
  // Retrieve GL_RUN variables from the level2 file
  //  
  S4version = S4Info(false); // we should decide how to handle versioning system
  //
  // create an interface to RunInfo called "runinfo"
  //
  runinfo = new ItoRunInfo(file);
  //
  // open "Run" tree in level2 file, if not existing return an error (sngl != 0)
  //
  sgnl = 0;
  sgnl = runinfo->Update(run,"S4",S4version);
  if ( sgnl ){
    //printf(" S4 - 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();
  UInt_t totnorun = runinfo->GetRunEntries();
  //
  // Try to access the S4 tree in the file, if it exists we are reprocessing data if not we are processing a new run
  //
  S4trclone = (TTree*)file->Get("S4");
  //
  if ( !S4trclone ){
    //
    // tree does not exist, we are not reprocessing
    //
    reproc = false;
    if ( run == 0 ){ 
      if (verbose) printf(" S4 - WARNING: you are reprocessing data but S4 tree does not exist!\n");
    }
    if ( runinfo->IsReprocessing() && run != 0 ) {
      if (verbose) printf(" S4 - WARNING: it seems you are not reprocessing data but S4\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?
    //
    S4trclone->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 S4 - 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 S4 - WARNING: Reprocessing run number %u \n",run);
      //
      // copying old tree to a new file
      //
      gSystem->MakeDirectory(S4folder.str().c_str());
      myfold = true;
      tempfile = new TFile(tempname.str().c_str(),"RECREATE");
      tempS4 = S4trclone->CloneTree(-1,"fast");
      tempS4->SetName("S4-old");
      tempfile->Write();
      tempfile->Close();  
    }
    //
    // Delete the old tree from old file and memory
    //
    S4trclone->Delete("all");
    //
    if (verbose) printf(" ...done!\n");
    //
  };
  //
  // create mydetector tree mydect
  // 
  file->cd();
  S4tr = new TTree("S4-new","PAMELA Level2 S4 data");
  S4tr->SetAutoSave(900000000000000LL);
  S4tr->Branch("S4Level2","S4Level2",&s4);
  //
  if ( reproc && !reprocall ){
    //
    //  open new file and retrieve also tree informations
    //
    tempfile = new TFile(tempname.str().c_str(),"READ");
    S4trclone = (TTree*)tempfile->Get("S4-old");
    S4trclone->SetAutoSave(900000000000000LL);
    S4trclone->SetBranchAddress("S4Level2",&s4clone);
    //      
    if ( nobefrun > 0 ){
      if (verbose){
	printf("\n Pre-processing: copying events from the old tree before the processed run\n");   
	printf(" Copying %u events in the file which are before the beginning of the run %u \n",nobefrun,run);
	printf(" Start copying at event number 0, end copying at event number %u \n",nobefrun);
      }
      for (UInt_t j = 0; j < nobefrun; j++){
	//
	S4trclone->GetEntry(j);	  
	//
	// copy s4clone to mydec
	//
	s4->Clear();
	//
	memcpy(&s4,&s4clone,sizeof(s4clone));
	//
	// Fill entry in the new tree
	//
	S4tr->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");
      printf("                    PROCESSING RUN NUMBER %u \n",idRun);
      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 ( debug ) printf(" S4 - 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 ( debug ) printf("\n S4 - 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 -504;
    stringstream myquery;
    myquery.str("");
    myquery << "SET time_zone='+0:00'";
    dbc->Query(myquery.str().c_str());
    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 -504;
    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());
      printf(" RUN HEADER absolute time is:  %u \n",runinfo->RUNHEADER_TIME);
      printf(" RUN TRAILER absolute time is: %u \n",runinfo->RUNTRAILER_TIME);
      printf(" %i events to be processed for run %u: from %u to %u \n\n",totevent,idRun,runinfo->EV_FROM,(runinfo->EV_FROM+totevent));
    }
    //
    //    if ( !totevent ) goto closeandexit;
    //
    // Open Level0 file
    //
    l0File = new TFile(fname.Data());
    if ( !l0File ) {
      if ( debug ) printf(" S4 - ERROR: problems opening  Level0 file\n");
      code = -6;
      goto closeandexit;
    };
    //
    l0tr = (TTree*)l0File->Get("Physics");
    if ( !l0tr ) {
      if ( debug ) printf(" S4 - ERROR: no Physics tree in Level0 file\n");
      l0File->Close();
      code = -7;
      goto closeandexit;
    };
    l0head = l0tr->GetBranch("Header");
    if ( !l0head ) {
      if ( debug ) printf(" S4 - ERROR: no Header branch in Level0 tree\n");
      l0File->Close();
      code = -8;
      goto closeandexit;    
    };
    l0S4 = l0tr->GetBranch("S4");
    if ( !l0S4 ) {
      if ( debug ) printf(" S4 - ERROR: no S4 branch in Level0 tree\n");
      l0File->Close();
      code = -503;
      goto closeandexit;
    };
    //
    l0tr->SetBranchAddress("S4", &l0s4e);
    l0tr->SetBranchAddress("Header", &eh); 
    //
    nevents = l0S4->GetEntries();
    //
    if ( nevents < 1 && totevent ) {
      if ( debug ) printf(" S4 - ERROR: Level0 file is empty\n\n");
      l0File->Close();
      code = -11;
      goto closeandexit;
    };
    //
    if ( runinfo->EV_TO > nevents-1 && totevent ) {
      if ( debug ) printf(" S4 - ERROR: too few entries in the S4 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)
    // second query: which is the value of paramfit relative to the calibration?
    //
    TArrayD *params = 0;
    params = S4_paramfit(runinfo->RUNHEADER_TIME, dbc);
    if ( !params ){
      code = -13;
      goto closeandexit;
    };
    //
    ParamFit0 = params->At(0);
    ParamFit1 = params->At(1);
    //
    // 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;
    };
    //
    for ( re = runinfo->EV_FROM; re < (runinfo->EV_FROM+runinfo->NEVENTS); re++){
      //
      if ( procev%1000 == 0 && procev > 0 && verbose ) printf(" %iK \n",procev/1000);	
      //
      l0head->GetEntry(re);
      //
      // absolute time of this event
      //
      ph = eh->GetPscuHeader();
      atime = dbtime->DBabsTime(ph->GetOrbitalTime());  
      //
      // paranoid check
      //
      if ( (atime > (runinfo->RUNTRAILER_TIME+1)) || (atime < (runinfo->RUNHEADER_TIME-1))  ) {
	if (verbose) printf(" S4 - WARNING: event at time outside the run time window, skipping it\n");
	goto jumpev;
      };
      //
      procev++;
      //
      // start processing
      //
      s4->Clear();
      l0S4->GetEntry(re);
      if (l0s4e->unpackError == 0){
	s4->S4adc = l0s4e->S4_DATA;
	//
	if ((l0s4e->S4_DATA) > 31 ){
	  s4->S4calibrated = ParamFit0*((l0s4e->S4_DATA)-32)+ParamFit1;
	}else{
	  s4->S4calibrated = 0;
	}
      };
      //
      s4->unpackError = l0s4e->unpackError;
      //
      S4tr->Fill();
      //    
      //
    jumpev:
      debug = false;
      //
    };
    //
    // Here you may want to clear some variables before processing another run  
    //
    delete dbtime;
    if ( params ) delete params;
    //
  }; // 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");   
	printf(" Copying %i events in the file which are after the end of the run %i \n",(int)(totfileentries-noaftrun),(int)run);
	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
	//
	S4trclone->GetEntry(j);	  
	//
	// copy s4clone to s4
	//
	//	s4 = new S4Level2();
	s4->Clear();
	memcpy(&s4,&s4clone,sizeof(s4clone));
	//
	// Fill entry in the new tree
	//
	S4tr->Fill();
      };
      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 ( runinfo ) runinfo->Close();    
  if ( S4tr ) S4tr->SetName("S4");    
  if ( file ){
    file->cd();
    file->Write();
  };
  //
  if ( myfold ) gSystem->Unlink(S4folder.str().c_str());
  //
  // the end
  //
  if (verbose) printf("\n Exiting...\n");
  if ( S4tr ) S4tr->Delete();
  //
  if ( s4 ) delete s4;
  if ( s4clone ) delete s4clone;
  if ( glroot ) delete glroot;
  if ( runinfo ) delete runinfo; 
  //
  if(code < 0)  throw code;
  return(code);
}


