#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 "UtlTime.hh"
#include "UtlArguments.hh"
#include "RcdArena.hh"

#include "RcdReaderAsc.hh"
#include "RcdReaderBin.hh"

#include "ChkCount.hh"
#include "HstCosmics.hh"
#include "EmcMap.hh"
#include "EmcEventAdc.hh"
#include "RcdEmcRawToAdc.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;
  //HstBase *hb(new HstCosmics(chipMask,-11.49,-14.75,!batch));

  //HstBase *hb(new HstCosmics(chipMask,-9.5,-15.0,!batch)); // 1102703739
  HstBase *hb(new HstCosmics(chipMask,-11.7,-14.8,!batch)); // 1102958829
  ChkCount ct;

  EmcMap emap;
  //emap.print(cout);
  RcdEmcRawToAdc r2a(emap);
  EmcEventAdc adc;

  ostringstream sout;
  sout << "dat/Run" << runNumber;
  reader.open(sout.str());

  /*
  ostringstream sout2;
  sout2 << "map/Map" << runNumber << ".txt";
  emap.read(sout2.str());
  */

  unsigned i(0);
  while(reader.read(arena)) {// && i<20) {
    ct.record(arena);

    //r2a.record(arena,adc);
    if(hb!=0) hb->record(arena);
    i++;
  }

  reader.close();
  ct.print(cout);

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