//
// L2ND.ccp -- standalone program to call the l2NDcore subroutine. 
//            
//
//   Version 3.00 17/05/2006: working.
//
// Changelog:
//
//  Input parameters must be now introduced by an identifier (-id run_id -file filename). Order does not matter.
//                           Added verbose/not verbose option.
//
//
// C/C++ headers
//
#include <iostream>
#include <sstream>
#include <TSystem.h>
//
// ROOT headers
//
#include <TString.h>
#include <TSQLServer.h>
//
// This package headers
//
#include <NDCore.h>
#include <NDVerl2.h>
//
using namespace std;
//
// Usage subroutine
//
void usage(){
  printf("\nUsage:\n");
  printf("\n NDLevel2 [-v] [-h] [--version] -idRun ID_RUN [-outDir outDir] [-processFile filename] [-processFolder folder]\n");
  printf("\n                   [-host host] [-user username] [-psw password]\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 -outDir         Path where to put the output [default ./] \n");
  printf("\n -processFile    output filename [default ID_RUN.Level2.root]\n");
  printf("\n -processFolder  folder for output data but the processFile [default \"NDFolder\"]\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 Notice that parameter order does not matter. \n");
  printf("\nExample: \n\nNDLevel2 -idRun 1085 -processFile nomefile.root\n\n");
};
//
Bool_t debug = false;
//
// Here the main
//
int main(int numinp, char *inps[]){
  //
  // Variables booking
  //
  TFile *processFile =0;
  int nul = 0;
  int error = 0;
  Bool_t beverbose = false;
  ULong64_t run = 0;
  TString filename="";
  TString processFolder;
  TString outDir = "./";
  TSQLServer *dbc = 0;
  Bool_t givenid = false;
  processFolder = "NDFolder";
  //
  TString host = "mysql://localhost/pamelaprod";
  TString user = "anonymous";
  TString psw = "";
  //
  // Checking input parameters
  //
   if ( numinp > 1 ){
    for ( int i = 0; i < numinp; i++ ){
      if ( !strcmp(inps[i],"--version") ){
	NDInfo(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();
	  exit(-3);
	};
	givenid = true;
	char *pEnd;	
	run = strtoull(inps[i+1],&pEnd,0);	
      };
      if ( !strcmp(inps[i],"-outDir") ) {
	if ( numinp-1 < i+1 ){
	  usage();
	  exit(-3);
	};
	outDir = (TString)inps[i+1];
      };	
      if ( !strcmp(inps[i],"-processFile") ) {
	if ( numinp-1 < i+1 ){
	  usage();
	  exit(-3);
	};
	filename = (TString)inps[i+1];	
      };
      if ( !strcmp(inps[i],"-processFolder") ) {
	if ( numinp-1 < i+1 ){
	  usage();
	  exit(-3);
	};
	processFolder = (TString)inps[i+1];	
      };
      if ( !strcmp(inps[i],"-host") ) {
	if ( numinp-1 < i+1 ){
	  usage();
	  exit(-3);
	};
	host = (TString)inps[i+1];	
      };
      if ( !strcmp(inps[i],"-user") ) {
	if ( numinp-1 < i+1 ){
	  usage();
	  exit(-3);
	};
	user = (TString)inps[i+1];	
      };
      if ( !strcmp(inps[i],"-psw") ) {
	if ( numinp-1 < i+1 ){
	  usage();
	  exit(-3);
	};
	psw = (TString)inps[i+1];	
      };
      if ( !strcmp(inps[i],"-v") || !strcmp(inps[i],"--verbose") ) beverbose = true;
    };
  } else {
    //
    // no input parameters exit with error, we need at least the run id.
    //
    printf("\n ND - ERROR: you must provide a run number (at least 0)\n\n");
    exit(-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 ) {
    printf("\n ND - ERROR: you must provide a run number (at least 0)\n\n");
    exit(-1);
  };
  //
  char *version = NDInfo(false);
  //
  // Start:
  //
  printf("\n Welcome to the ND LEVEL2 flight software, version %s \n",version);
  //
  // Connect to the DB
  //
  printf("\nConnecting to database... \n"); 
  //
  dbc = TSQLServer::Connect(host.Data(),user.Data(),psw.Data());
  if( !dbc ) {
    printf(" ND - ERROR: problems connecting to the DB (check username and passwd), exiting...\n\n");
    exit(-2);    
  };
  bool connect = dbc->IsConnected();
  //
  if( !connect ) {
    printf(" ND - ERROR: problems connecting to the DB (check username and passwd), exiting...\n\n");
    exit(-2);    
  };
  printf("...connected! \n\n");
  //
    if ( filename.IsNull() ){
      stringstream strun;
      strun.str("");
      strun << run;
      filename += strun.str();
      filename += ".Level2.root";
    };
    filename = outDir + "/" + filename;
    processFile = new TFile(filename.Data(),"UPDATE");
  //
  // Run the core program, put any output error in the "error" variable
  //
  error = NDCore(run, processFile,dbc, numinp, inps);
  //
  // Close the DB connection
  //
  printf("\nClose the connection to the database... \n");
  dbc->Close();
  printf("...connection terminated!\n\n");   
  //
  // Close redirection if the case.
  //
  if ( !beverbose ) close(nul);
  //
  // Return "error"
  //
  if ( error > 0 ) printf(" ND - WARNING: exiting with signal %i \n\n",error);
  if ( error < 0 ) printf(" ND - ERROR: exiting with signal %i \n\n",error);
  processFile->Close();
  exit(error);
}
