#include <unistd.h>

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

#include "UtlArguments.hh"
#include "RcdArena.hh"
#include "RcdReaderAsc.hh"
#include "RcdReaderBin.hh"
#include "DspCosmics3.hh"
#include "HstCosmics4.hh"
#include "EmcMap.hh"
#include "EmcEventAdc.hh"
#include "EmcPedestals.hh"
#include "RcdEmcRawToAdc.hh"
#include "EmcPedestals.hh"
#include "EmcEnergies.hh"
#include "ChkCount.hh"

using namespace std;

int main(int argc, const char **argv) {
  UtlArguments argh(argc,argv);
  //argh.print(cout);
  const bool useReadAsc(argh.option('a',"Ascii input file"));
  const unsigned nEvents(argh.optionArgument('e',0xffffffff,"Number of events"));

  const unsigned nRuns(1);
  const unsigned runs[nRuns]={100083};

  RcdArena r;

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

  EmcEventAdc ad;
  EmcEventEnergy en;

  EmcMap mp;
  EmcCalibration cl;

  RcdEmcRawToAdc r2a(mp);
  EmcPedestals pd(cl);
  EmcEnergies eg(cl);
  HstCosmics4 ht(0xffff,0.0,0.0,false);
  //DspCosmics3 display;
  ChkCount ct;

  unsigned iEvent(0);

  for(unsigned iRun(0);iRun<nRuns && iEvent<nEvents;iRun++) {
    ostringstream sout;
    sout << runs[iRun];

    assert(reader->open(std::string("data/dat/Run")+sout.str()));

    assert(mp.read(std::string("data/map/Map")+sout.str()+".txt"));
    //mp.print(cout);

    while(reader->read(r) && iEvent<nEvents) {
      ct.record(r);
      
      if(r.recordType()==RcdHeader::event) {
	if((iEvent%1000)==0) cout << "Event = " << iEvent << endl;

	r2a.record(r,ad);
	//ad.print(cout);
	
	eg.event(ad,en);
	//en.print(cout);
	
	pd.event(ad);
	
	// Do the analysis
	ht.event(r,en);
	
	//if(iEvent=1234) {
	//display.event(r,en);
	//sleep(1);

	iEvent++;
      }
    }

    reader->close();
  }

  ht.postscript("cosmics4.ps");
  ct.print(cout);

  delete reader;

  return 0;
}
