#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
#include <fcntl.h>
#include <unistd.h>

#include <iostream>
#include <sstream>
#include <vector>
#include <cstdio>

#include "UtlArguments.hh"

#include "DaqRunStart.hh"
#include "RcdArena.hh"
#include "RcdReaderAsc.hh"
#include "RcdReaderBin.hh"

#include "HstSlwMonLm82_catherine.hh"

using namespace std;

int main(int argc, const char **argv) {
  UtlArguments argh(argc,argv);
  //argh.print(cout);

  const bool batch(argh.option('b',"Select batch mode for ROOT"));
  const bool useReadAsc(argh.option('a',"Ascii input file"));
  const bool slwRead(argh.option('s',"Slow data input file"));

  const unsigned vnum(argh.lastArgument(999999));
  std::ostringstream run;
  run << vnum;


  if(argh.help()) return 0;

  if(batch) cout << "ROOT batch mode selected" << endl;
  else      cout << "ROOT interactive mode selected" << endl;

  RcdArena arena;

  RcdReader *reader(0);
  if(useReadAsc){
    reader=new RcdReaderAsc();
    cout << "Reading an ascii file" << endl;
  }
  else{
    reader=new RcdReaderBin();
    cout << "Reading a binary file" << endl;
  }

  CrcLocationData<CrcLm82SlowReadoutData> dl;
  HstSlwMonLm82_catherine *hl=new HstSlwMonLm82_catherine(dl,!batch);
  
  std::ostringstream sout2;
  if(slwRead) sout2 << "data/sum/Slw" << run.str() << "_slowLm82.ps";
  else        sout2 << "data/sum/Run" << run.str() << "_slowLm82.ps";

  std::ostringstream sout;
  if(slwRead) sout << std::string("data/slw/Slw")+run.str();
  else        sout << std::string("data/dat/Run")+run.str();
  reader->open(sout.str());
  
  unsigned count(0);
  
  while(reader->read(arena)) {
    if(hl!=0) hl->record(arena);
    count++;
  }
  
  reader->close();
  hl->update();
  if(hl!=0) {
    hl->postscript(sout2.str());
    delete hl;
  }

  delete reader;
  
}
