#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 "HstNoise.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 unsigned chipMask(argh.optionArgument('c',0xfff,"Chip mask"));
  const unsigned runNumber(argh.lastArgument(999999));

  if(argh.help()) return 0;

  if(batch) cout << "ROOT batch mode selected" << endl;
  else      cout << "ROOT interactive mode selected" << endl;
  cout << "Chip mask set to " << printHex((unsigned short)chipMask) << endl;
  cout << "Run number set to " << runNumber << endl;

  RcdArena arena;
  RcdReaderAsc reader;

  HstNoise *hb=new HstNoise(14,chipMask);

  std::ostringstream sout;
  sout << "/localstage/calice/dat/Run" << runNumber;
  reader.open(sout.str());

  while(reader.read(arena)) {

    //for(unsigned i(0);i<100;i++) {
    //reader.read(arena);

    if(hb!=0) hb->event(arena);
  }

  reader.close();
  //hb->update();
  hb->update(true);

  sleep(60);

  if(hb!=0) {
    std::ostringstream sout;
    sout << "dps/Run" << runNumber << ".ps";
    //hb->postscript(sout.str());
    delete hb;
  }
}
