#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>

// dual/inc/utl
#include "UtlTime.hh"
#include "UtlArguments.hh"

// dual/inc/rcd
#include "RcdArena.hh"
#include "RcdReaderAsc.hh"
#include "RcdReaderBin.hh"
#include "RunReader.hh"
#include "RcdMultiUserRO.hh"

// dual/inc/daq
#include "DaqRunStart.hh"

// dual/inc/chk
#include "ChkCount.hh"
#include "ChkCheck.hh"
//#include "ChkDaqData.hh"
#include "ChkPrint.hh"

using namespace std;


int main(int argc, const char **argv) {
  UtlArguments argh(argc,argv);

  const bool useReadAsc(argh.option('a',"Ascii input file"));
  const unsigned printLevel(argh.optionArgument('p',0,"Print level"));
  const unsigned numberOfRecords(argh.optionArgument('r',0x7fffffff,
                                                     "Number of records"));
  const unsigned numberOfSkips(argh.optionArgument('k',0,
                                                     "Number of records to skip"));
  const unsigned runNumber(argh.lastArgument(999999));
  
  if(argh.help()) return 0;

  if(useReadAsc) cout << "Ascii input file selected" << endl;
  else           cout << "Binary input file selected" << endl;
  cout << "Print level set to " << printLevel << endl;
  cout << "Number of records set to " << numberOfRecords << endl;
  cout << "Run number set to " << runNumber << endl;
  cout << endl;

#ifdef OLD_READER
  RcdReader *reader(0);
  if(useReadAsc) reader=new RcdReaderAsc();
  else           reader=new RcdReaderBin();

  ostringstream sout;
  sout << runNumber;
  if(!reader->open(std::string("data/dat/Run")+sout.str())) return 1;
#else
  RunReader theReader;
  RunReader *reader(&theReader);
  assert(reader->open(runNumber,useReadAsc));
#endif

  RcdMultiUserRO rmu;
  rmu.printLevel(printLevel);

  ChkCount hn;
  //hn.printRecord(RcdHeader::runEnd);
  //hn.printRecord(RcdHeader::runStop);
  rmu.addUser(hn);

  ChkCheck ch(5);
  rmu.addUser(ch);

  //ChkDaqData cdd;
  //rmu.addUser(cdd);

  ChkPrint pr;
  pr.enableType(false);
  pr.enable(false);

  RcdArena arena;
  unsigned iRecords(0);
  while(reader->read(arena) && iRecords<numberOfRecords) {
    iRecords++;
    if(iRecords>numberOfSkips) {
      pr.record(arena);
      assert(rmu.record(arena));
    }
  }

  ch.print(cout);
  //cdd.print(cout);
  
  if(!reader->close()) return 2;

  return 0;
}
