//#define HST_MAP

#include <iostream>
#include <fstream>
#include <sstream>

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

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

// dual/inc/chk
#include "FixEmc.hh"
#include "FixAhc.hh"
#include "ChkCount.hh"
#include "ChkPrint.hh"
#include "HstGeneric.hh"
#include "HstTFile.hh"
#include "HstTimers.hh"
//#include "HstGeneOff.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 bool slwRead(argh.option('s',"Slow data input file"));
  const unsigned printLevel(argh.optionArgument('p',0,"Print level"));
  const unsigned numberOfRecords(argh.optionArgument('r',0xffffffff,
						     "Number of records"));
  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;
  if(!slwRead) cout << "Normal data file selected" << endl;
  else        cout << "Slow data 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;

  RunReader theReader;
  RunReader *reader(&theReader);

  ChkCount hn;
  hn.printLevel(printLevel);
  ChkPrint hp;
  hp.printLevel(printLevel);
  hp.enable(subRecordType< CrcLocationData<CrcBeTrgConfigurationData> >(),true);
  hp.enable(subRecordType<DaqConfigurationStart>(),true);
  hp.enable(subRecordType<DaqConfigurationEnd>(),true);

  HstTFile amm(argh.processName()+".root");
  HstTimers ht;
  ht.printLevel(printLevel);

  /*
  TFile *hfile = TFile::Open("hstAmm.root","CREATE");
  if (!hfile) {
    unsigned overwrite;
    cout << " ----> Do you want to overwrite it ? 0: No, 1: yes" << endl;
    cin >> overwrite;
    if (overwrite == 0) exit(0);
  } else {
    hfile = TFile::Open("hstAmm.root","RECREATE");
  }
  */

  RcdArena arena;
  unsigned iRecords(0);

  assert(reader->open(runNumber,useReadAsc));

  //while(true) {
  while(reader->read(arena) && iRecords<numberOfRecords) {
    iRecords++;
    //assert(fe.fix(arena));
    //assert(fa.fix(arena));
    assert(hn.record(arena));
    assert(ht.record(arena));
    assert(hp.record(arena));
    assert(amm.record(arena));
  }
  
  assert(reader->close());
    //}

  /*    
  hfile->Write();
  cout << endl << endl << "After writing output ROOT file"<< endl;
  hfile-> Close();
  delete hfile;
  hfile =0;
  */
  return 0;
}
