//
// C/C++ headers
//
#include <fstream>
#include <string.h>
#include <iostream>
#include <cstring>
#include <stdio.h>
//
// ROOT headers
//
#include <TTree.h>
#include <TClassEdit.h>
#include <TObject.h>
#include <TList.h>
#include <TArrayL.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>
//
// YODA headers
//
#include <PamelaRun.h>
#include <RegistryEvent.h>
#include <PscuHeader.h>
#include <PscuEvent.h>
#include <EventHeader.h>
#include <RegistryEvent.h>
#include <CalibS4Event.h>
#include <physics/S4/S4Event.h>
//#include <yodaUtility.h>
//
// RunInfo header
//
#include <RunInfo.h>
#include <GLTables.h>
//
// This program headers
//
#include <S4Level2.h>
#include <S4Core.h>
#include <S4Verl2.h>

using namespace std;

//
// CORE ROUTINE
//
//

int S4Core(ULong64_t run, TFile *file, TSQLServer *dbc, Int_t S4argc, char *S4argv[]){
  Int_t i = 0;
  //
  TString processFolder = "S4Folder";
  //
  // Set these to true to have a very verbose output.
      Bool_t debug = false;
  //
      Bool_t verbose = false;
  //    
  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;
      };
      if ( (!strcmp(S4argv[i],"--verbose")) || (!strcmp(S4argv[i],"-v"))) {
	verbose = true;
      };
      i++;
    };
  };
 
  const char* outDir = gSystem->DirName(gSystem->DirName(file->GetPath()));
  // Variables for level2 
  //
  TTree *S4tr = 0;
  Long64_t nevents = 0LL;
  //
  // variables needed to reprocess data
  //
  TString S4version;
  ItoRunInfo *runinfo = 0;
  TArrayL *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;
  Long64_t totfileentries = 0ULL;
  Long64_t idRun = 0LL;
  Double_t  ParamFit0 =  0ULL; 
  Double_t  ParamFit1 =  0ULL; 
  //
  // 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 *l0registry = 0;
  TBranch *l0S4 =0;
  pamela::RegistryEvent *l0reg=0;
  pamela::S4::S4Event  *l0s4e = 0;
  pamela::EventHeader *eh = 0;
  //
  // Define other basic variables
  // 
  UInt_t procev = 0;
  stringstream file2;
  stringstream file3;
  stringstream qy;
  Int_t totevent = 0;
  ULong64_t atime = 0ULL;
  Int_t ei = 0; 
  Int_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;
  tempname.str("");
  tempname << outDir;
  tempname << "/" << processFolder.Data();
  S4folder.str("");
  S4folder << tempname.str().c_str();
  gSystem->MakeDirectory(S4folder.str().c_str());
  tempname << "/S4tree_run";
  tempname << run << ".root";  
  //
  // DB classes
  //
  GL_ROOT *glroot = new GL_ROOT();
  GL_S4_CALIB *glS4calib = new GL_S4_CALIB();
  //
  // 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 == 0ULL )  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();
  //
  // 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 == 0ULL ){ 
      if (verbose) printf(" S4 - WARNING: you are reprocessing data but S4 tree does not exist!\n");
    }
    if ( runinfo->IsReprocessing() && run != 0ULL ) {
      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?
    //
    reproc = true;
    //
    // update versioning information 
    //
    //sgnl = runinfo->Update(run, "S4",S4version);
    if (verbose) printf("\n Preparing the pre-processing...\n");
    //
    if ( run == 0ULL ){
      //
      // 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 %llu \n",run);
      //
      // copying old tree to a new file
      //
      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->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->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 %llu \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 = new S4Level2();
	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 %i \n",(int)idRun);
      printf(" ####################################################################### \n\n\n");
    }
    //
    runinfo->ID_REG_RUN = 0ULL;
    //
    // store in the runinfo class the GL_RUN variables for our run
    //
    sgnl = 0;
    sgnl = runinfo->GetRunInfo(idRun);
    if ( sgnl ){
      //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_REG_RUN
    //
    if ( runinfo->ID_REG_RUN == 0 ){
      //printf("\n S4 - ERROR: no run with ID_RUN = %i \n\n Exiting... \n\n",(int)idRun);
      code = -5;
      goto closeandexit;    
    };
    //
    // Search in the DB the path and name of the LEVEL0 file to be processed.
    //
    glroot->Query_GL_ROOT(runinfo->ID_REG_RUN,dbc);
    //
    ftmpname.str("");
    ftmpname << glroot->PATH.Data() << "/";
    ftmpname << glroot->NAME.Data();
    fname = ftmpname.str().c_str();
    //
    // print out informations
    //
    totevent = runinfo->EV_REG_PHYS_TO - runinfo->EV_REG_PHYS_FROM + 1;
    if (verbose){
      printf("\n LEVEL0 data file: %s \n",fname.Data());
      printf(" RUN HEADER absolute time is:  %llu \n",runinfo->RUNHEADER_TIME);
      printf(" RUN TRAILER absolute time is: %llu \n",runinfo->RUNTRAILER_TIME);
      printf(" %i events to be processed for run %llu: from %i to %i (reg entries)\n\n",totevent,idRun,runinfo->EV_REG_PHYS_FROM,runinfo->EV_REG_PHYS_TO);
    }
    //
    // Open Level0 file
    //
    l0File = new TFile(fname.Data());
    if ( !l0File ) {
      //printf(" S4 - ERROR: problems opening  Level0 file\n");
      code = -6;
      goto closeandexit;
    };
    l0tr = (TTree*)l0File->Get("Physics");
    if ( !l0tr ) {
      //printf(" S4 - ERROR: no Physics tree in Level0 file\n");
      l0File->Close();
      code = -7;
      goto closeandexit;
    };
    l0head = l0tr->GetBranch("Header");
    if ( !l0head ) {
      //printf(" S4 - ERROR: no Header branch in Level0 tree\n");
      l0File->Close();
      code = -8;
      goto closeandexit;    
    };
    l0registry = l0tr->GetBranch("Registry");
    if ( !l0registry ) {
      //printf(" S4 - ERROR: no Registry branch in Level0 tree\n");
      l0File->Close();
      code = -9;
      goto closeandexit;    
    };
    l0S4 = l0tr->GetBranch("S4");
    if ( !l0S4 ) {
      //printf(" S4 - ERROR: no S4 branch in Level0 tree\n");
      l0File->Close();
      code = -503;
      goto closeandexit;
    };

    //
    l0tr->SetBranchAddress("Registry", &l0reg);
    l0tr->SetBranchAddress("S4", &l0s4e);
    l0tr->SetBranchAddress("Header", &eh); 
    //
    nevents = l0registry->GetEntries();
    //
    if ( nevents < 1 ) {
      //printf(" S4 - ERROR: Level0 file is empty\n\n");
      l0File->Close();
      code = -11;
      goto closeandexit;
    };
    //
    if ( runinfo->EV_REG_PHYS_TO > nevents-1 ) {
      //printf(" S4 - 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)
    // second query: which is the value of paramfit relative to the calibration?
    //
    glS4calib->Query_GL_S4_CALIB(runinfo->RUNHEADER_TIME, dbc);
    ParamFit0 = glS4calib->PARAM_FIT0;
    ParamFit1 = glS4calib->PARAM_FIT1;
    //
    // run over all the events of the run
    //
    if (verbose) printf("\n Ready to start! \n\n Processed events: \n\n");
    //
    for ( re = runinfo->EV_REG_PHYS_FROM; re <= runinfo->EV_REG_PHYS_TO; re++){
      //
      if ( procev%1000 == 0 && procev > 0 && verbose ) printf(" %iK \n",procev/1000);	
      //
      l0registry->GetEntry(re);
      //
      // absolute time of this event
      //
      atime = l0reg->absTime;
      //
      // physics events is at entry number ei where
      //
      ei = l0reg->event;
      //
      // paranoid check
      //
      if ( (atime > runinfo->RUNTRAILER_TIME) || (atime < runinfo->RUNHEADER_TIME)  ) {
	if (verbose) printf(" S4 - WARNING: event at time outside the run time window, skipping it\n");
	goto jumpev;
      };
      //
      procev++;
      //
      // start processing
      //
      s4 = new S4Level2();
      l0S4->GetEntry(ei);
      if (l0s4e->unpackError == 1)  continue;      
      s4->S4adc = l0s4e->S4_DATA;
      if ((l0s4e->S4_DATA) > 31 ){
	s4->S4calibrated = ParamFit0*((l0s4e->S4_DATA)-32)+ParamFit1;
      }else{
	s4->S4calibrated = 0;
      }
      S4tr->Fill();
      //    
      //
    jumpev:
      debug = false;
      //
    };
    //
    // Here you may want to clear some variables before processing another run  
    //
    ei = 0;
  }; // 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();
	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();            
  gSystem->Unlink(tempname.str().c_str());

  //if ( code < 0 ) printf("\n S4 - ERROR: an error occurred, try to save anyway...\n");
  //printf("\n Writing and closing rootple\n");
  if ( runinfo ) runinfo->Close();    
  if ( S4tr ) S4tr->SetName("S4");    
  if ( file ){
    file->cd();
    file->Write();
  };
  //
  gSystem->Unlink(S4folder.str().c_str());
  //
  // the end
  //
  if (verbose) printf("\n Exiting...\n");
  if(S4tr)S4tr->Delete();
  if(code < 0)  throw code;
  return(code);
}