//
// C/C++ headers
//
#include <iostream>
#include <sstream>
//
// ROOT headers
//
#include <TString.h>
#include <TSQLServer.h>
#include <TFile.h>
#include <TSystem.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;
//
//
//
#include <DarthVaderVerl2.h>
//
// Usage subroutine
//
void usage(){
  printf("\nUsage:\n");
  printf("\n DarthVader [-v | --verbose] [-h | --help] [--version] -idRun ID_RUN [-processFile filename]\n");
  printf("\n            [-host host] [-user username] [-psw password] [+-all] [+-detector [detector options] ]\n");
  printf("\n --version       print informations about compilation and exit\n");
  printf("\n -h | --help     print this help and exit \n");
  printf("\n -v | --verbose  be verbose [default: print nothing on STDOUT]\n");
  printf("\n -idRun          ID_RUN: ID number of the run to be processed \n");
  printf("\n -processFile    output filename [default ID_RUN.Level2.root]\n");
  printf("\n -host           name for the host [default = mysql://localhost/pamelaprod]\n");
  printf("\n -user           username for the DB [default = anonymous] \n");
  printf("\n -psw            password for the DB [default = \"\"]\n");
  printf("\n +all            call all detectors software [default]\n");
  printf("\n -all            call nothing\n");
  printf("\n +detector       process detector; detector can be: TOF,TRK,CAL,TRG,ORB,S4,ND,AC,RUN\n");
  printf("\n -detector       do not process detector (as above)\n");
  printf("\nExamples: \n");
  printf("\nStandard call: DarthVader -idRun 1085 \n");
  printf("\nProcess only RunInfo and Tracker (be verbose for tracker): DarthVader -idRun 1085 -all +RUN +TRK [ --verbose ] \n");
  printf("\nProcess all and be verbose for calorimeter: DarthVader -idRun 1085 +CAL [ --verbose ] \n\n");
};
//
// Here the main
//
int main(int numinp, char *inps[]){
  //
  // Variables booking
  //
  TString message;
  int nul = 0;
  Int_t error = 0;
  //
  Int_t CALSGN = 0;
  Int_t TRKSGN = 0;
  Int_t TRGSGN = 0;
  Int_t TOFSGN = 0;
  Int_t RUNSGN = 0;
  Int_t ORBSGN = 0;
  Int_t ACSGN = 0;
  Int_t S4SGN = 0;
  Int_t NDSGN = 0;
  //
  Bool_t debug = false;
  Bool_t beverbose = false;
  Bool_t givenid = 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];
  //
  //
  //
  ULong64_t run = 0;
  //
  TString filename;
  TString outDir =  gSystem->WorkingDirectory(); 
  //
  TSQLServer *dbc = 0;
  TString host = "mysql://localhost/pamelaprod";
  TString user = "anonymous";
  TString psw = "";
  //
  TFile *processFile = 0;
  //
  // Checking input parameters
  //
  Int_t i = 0;
  try {
    if ( numinp > 1 ){
      while ( i < numinp ){
	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;
	  };
	  givenid = true;
	  char *pEnd;	
	  run = strtoull(inps[i+1],&pEnd,0);	
	};
	if ( !strcmp(inps[i],"-processFile") ) {
	  if ( numinp-1 < i+1 ){
	    usage();
	    throw -3;
	  };
	  filename = (TString)inps[i+1];	
	};
	if ( !strcmp(inps[i],"-outDir") ) {
	  if ( numinp-1 < i+1 ){
	    usage();
	    throw -3;
	  };
	  outDir = (TString)inps[i+1];	
	};
	if ( !strcmp(inps[i],"-host") ) {
	  if ( numinp-1 < i+1 ){
	    usage();
	    throw -3;
	  };
	  host = (TString)inps[i+1];	
	};
	if ( !strcmp(inps[i],"-user") ) {
	  if ( numinp-1 < i+1 ){
	    usage();
	    throw -3;
	  };
	  user = (TString)inps[i+1];	
	};
	if ( !strcmp(inps[i],"-psw") ) {
	  if ( numinp-1 < i+1 ){
	    usage();
	    throw -3;
	  };
	  psw = (TString)inps[i+1];	
	};
	if ( !strcmp(inps[i],"-v") || !strcmp(inps[i],"--verbose") ) beverbose = true;
	//
	if ( !strcmp(inps[i],"-g") || !strcmp(inps[i],"--debug") ) debug = true;
	//
	if ( !strcmp(inps[i],"-CAL") ) {
	  CAL = false;
	};
	if ( !strcmp(inps[i],"-TRK") ) {
	  TRK = false;
	};
	if ( !strcmp(inps[i],"-TOF") ) {
	  TOF = false;
	};
	if ( !strcmp(inps[i],"-TRG") ) {
	  TRG = false;
	};
	if ( !strcmp(inps[i],"-S4") ) {
	  S4 = false;
	};
	if ( !strcmp(inps[i],"-ND") ) {
	  ND = false;
	};
	if ( !strcmp(inps[i],"-AC") ) {
	  AC = false;
	};
	if ( !strcmp(inps[i],"-RUN") ) {
	  RUN = false;
	};
	if ( !strcmp(inps[i],"-ORB") ) {
	  ORB = false;
	};
	//
	if ( !strcmp(inps[i],"-all") ) {
	  CAL = false;
	  ORB = false;
	  TRK = false;
	  TRG = false;
	  TOF = false;
	  S4 = false;
	  ND = false;
	  AC = false;
	  RUN = false;
	};
	//
	if ( !strcmp(inps[i],"+all") ) {
	  CAL = true;
	  ORB = true;
	  TRK = true;
	  TRG = true;
	  TOF = true;
	  S4 = true;
	  ND = true;
	  AC = true;
	  RUN = true;
	};
	//
	if ( !strcmp(inps[i],"+CAL") ) {
	  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") ) {
	  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") ) {
	  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") ) {
	  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") ) {
	  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") ) {
	  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") ) {
	  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") ) {
	  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") ) {
	  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;
	      };
	    };
	  };
	};
	//
	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_IREAD | S_IWRITE);
      dup2(nul,1);
      dup2(nul,2);
    };
    //
    // Check that an input run number has been given
    //
    if ( !givenid ) throw -1;
    //
    char *version = DarthVaderInfo(false);
    //
    // Start:
    //
    printf("\n Welcome to the PAMELA LEVEL2 flight software, version %s \n\n",version);
    //
    // 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 connect = dbc->IsConnected();
    //
    if( !connect ) throw -2;    
    //
    if ( debug ) printf("...connected! \n\n");
    //
    // 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";
    };
    //    filename = outDir + "/" + filename;
    processFile = new TFile(filename.Data(),"UPDATE");
    if ( !processFile->IsOpen() ) throw -15;    
    //
    // Run the core program, put any output error in the "error" variable
    //
    if ( RUN ) {
      printf(" Calling RunInfo... ");
      RUNSGN = RunInfoCore(run,processFile,dbc,runargc,runargv);
      printf("done\n");
    };
    //
    // From the Run Infos extract acq_var_info to determine if detectors are in the acquisition or not
    //
    printf(" Checking if requested detectors are in the acquisition\n");
    ItoRunInfo *runinfo = new ItoRunInfo(processFile);
    runinfo->Read(run);
    printf(" => ACQ_VAR_INFO = %i \n",runinfo->ACQ_VAR_INFO);
    if ( TRK && !(runinfo->ACQ_VAR_INFO & (1 << 4)) ) throw -16;
    if ( TOF && !(runinfo->ACQ_VAR_INFO & (1 << 0)) ) throw -17;
    if ( CAL && !(runinfo->ACQ_VAR_INFO & (1 << 3)) ) throw -18;
    if ( AC  && !(runinfo->ACQ_VAR_INFO & (1 << 1)) && !(runinfo->ACQ_VAR_INFO & (1 << 2)) ) throw -19;
    if ( S4  && !(runinfo->ACQ_VAR_INFO & (1 << 5)) ) throw -20;
    if ( ND  && !(runinfo->ACQ_VAR_INFO & (1 << 9)) ) throw -21;
    printf(" OK! start processing detector's data. \n");
    //
    if ( TRK ) {
      printf(" Calling TrackerLevel2... ");
      TRKSGN = TrkCore(run,processFile,dbc,trkargc,trkargv);
      printf("done\n");
    };
    if ( TOF ) {
      printf(" Calling ToFLevel2... ");
      TOFSGN = ToFCore(run,processFile,dbc,tofargc,tofargv);
      printf("done\n");
    };
    if ( CAL ) {
      printf(" Calling CalorimeterLevel2... ");
      CALSGN = CaloCore(run,processFile,dbc,calargc,calargv);
      printf("done\n");
    };
    if ( TRG ) {
      printf(" Calling TriggerLevel2... ");
      TRGSGN = TrigCore(run,processFile,dbc,trgargc,trgargv);
      printf("done\n");
    };
    if ( AC ) {
      printf(" Calling AnticounterLevel2... ");
      ACSGN = AcCore(run,processFile,dbc,acargc,acargv);
      printf("done\n");
    };
    if ( S4 ) {
      printf(" Calling S4Level2 ... ");
      S4SGN = S4Core(run,processFile,dbc,s4argc,s4argv);
      printf("done\n");
    };
    if ( ND ) {
      printf(" Calling NDLevel2... ");
      NDSGN = NDCore(run,processFile,dbc,ndargc,ndargv);
      printf("done\n");
    };
    if ( ORB ) {
      printf(" Calling OrbitalInfo... ");
      ORBSGN = OrbitalInfoCore(run,processFile,dbc,orbargc,orbargv);
      printf("done\n");
    };    
    //
  } 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 -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 registry 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 -16:  message += " No tracker in the acquisition (use -TRK to process anyway)"; break;
    case -17:  message += " No ToF in the acquisition (use -TOF to process anyway)"; break;
    case -18:  message += " No calorimeter in the acquisition (use -CAL to process anyway)"; break;
    case -19:  message += " No anticounters in the acquisition (use -AC to process anyway)"; break;
    case -20:  message += " No S4 in the acquisition (use -S4 to process anyway)"; break;
    case -21:  message += " No neutron detector in the acquisition (use -ND to process anyway)"; 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_CALO_CALIB query"; 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 -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 -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 -313: message += " TOFLEVEL2 - No more tracker 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 -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 -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 -701: message += " NDLEVEL2 - Cannot open file for writing"; break;
    case -704: message += " NDLEVEL2 - No Anticounter branch in Level0 tree"; 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;
      //
    default: message += "Unidentified error or warning"; break;
    };
    printf("\n");
    if ( signal < 0 ) cout << " ERROR ("<< signal << ") "<< message <<endl;
  }
  //  switch(RUNSGN){
  //  };
  switch(CALSGN){
  case 100: printf("\n WARNING CALORIMETER - Data with no associated calibration\n"); break;
  case 101: printf("\n WARNING CALORIMETER - No tracks or good events in this run\n"); break;
  };
  //
  // 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->Close();
  };
  //
  if ( error != 0 ) printf("\n\n WARNING: exiting with signal %i \n\n",error);
  printf("\n");
  //
  // Close redirection if the case.
  //
  if ( !beverbose ) close(nul);
  //
  //
  exit(error);
}
