//
// EventViewer.cc -- standalone program to call the EventViewer macro. 
//    by Emiliano Mocchiutti
//
//   Version 1.00 (2005/11/07)
//
// Changelog: 
//
// 0.00 - 1.00 : working.
//
#include <TSystem.h>
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
//
#include <FEventViewerCore.h>
#include <FEVVerl2.h>
//
using namespace std;
//
int main(int numinp, char *inps[]){
  TString name = "";
  TString selfile = "";
  TString outdir = "";
  bool beverbose = false;
  if ( numinp > 1 ){
    if ( !strcmp(inps[1],"--version") ){
      FEVInfo(true);
      return(0);
    };
    if ( !strcmp(inps[1],"-h") || !strcmp(inps[1],"--help") || numinp>7 ){
      printf("\nUsage:\n\n EventViewer [-v] file selection_file output_dir \n");
      printf("\n -v                be verbose and do not fork after launching the GUI\n");
      printf(  "  file             must be in the form: /path/to/filesfromyoda/dw_000000_00000/  \n");
      printf(  "  selection_file   selection file, empty if no selection is required \n");
      printf(  "  outDir           directory where to save figures\n");
      printf("\nExamples: \n\nEventViewer /home/pamela/filesfromyoda/dw_050301_00100/ \"\" /home/pamela/\n");
      printf(                "EventViewer -v /home/pamela/filesfromyoda/dw_050301_00100/ muselection.c \"\"\n\n");
      printf(                "EventViewer \n\n");
      printf(                "EventViewer -v \n\n");
      return(0);
    };
    if ( !strcmp(inps[1],"-v") || !strcmp(inps[1],"--verbose") ){
      beverbose = true;
      if ( numinp >= 3 ) name = (TString)inps[2];
      if ( numinp >= 4 ) selfile = (TString)inps[3];
      if ( numinp == 5 ) outdir = (TString)inps[4];
    } else {
      name = (TString)inps[1];
      if ( numinp >= 3 ) selfile = (TString)inps[2];
      if ( numinp >= 4 ) outdir = (TString)inps[3];
    };
  };
  if ( beverbose ){
    ShowEvent(name,selfile,outdir);
  } else {
    //
    // redirect to dev/null the stdout
    //
    int nul;
    nul = open("/dev/null", O_CREAT | O_RDWR,S_IREAD | S_IWRITE);
    dup2(nul,1);
    dup2(nul,2);
    close(nul);
    //
    printf("\n Welcome to  the PAMELA event viewer! \n\n");
    //
    // fork process
    //
    pid_t pid;
    if( (pid=fork()) == -1 ){
      fprintf(stderr," Fork error. Exiting.\n"); 
      exit(1);        
    };
    if( !pid ) {
      ShowEvent(name,selfile,outdir);
    };
  };
  //
  return(0);
}
