#include <unistd.h>

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

#include "UtlArguments.hh"
#include "RcdArena.hh"
#include "RcdReaderAsc.hh"
#include "RcdReaderBin.hh"
#include "RcdReaderSkt.hh"
#include "DspCosmics3.hh"
#include "EmcMap.hh"
#include "EmcEventAdc.hh"
#include "EmcPedestals.hh"
#include "RcdEmcRawToAdc.hh"
#include "RcdEmcStageFix.hh"
#include "EmcPedestals.hh"
#include "EmcEnergies.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 bool useReadSkt(argh.option('k',"Socket input"));
  const unsigned psEvent(argh.optionArgument('e',1000000000,"Event to postscript"));
  const unsigned nSleep(argh.optionArgument('s',1,"Sleep time between events (secs)"));
  const unsigned vnum(argh.lastArgument(999999));

  if(argh.help()) return 0;

  std::ostringstream sout;
  sout << vnum;

  RcdReader *reader(0);
  if(useReadAsc) {
    reader=new RcdReaderAsc();
  } else {
    if(useReadSkt) reader=new RcdReaderSkt();
    else           reader=new RcdReaderBin();
  }

  if(useReadSkt) {
    if(!reader->open("131.169.61.122")) return 0;
  } else {
    if(!reader->open(std::string("data/dat/Run")+sout.str())) return 0;
  }

  RcdArena r;
  EmcEventAdc ad;
  EmcEventEnergy en;

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

  RcdEmcRawToAdc r2a(mp);
  EmcPedestals pd(cl);
  EmcEnergies eg(cl);
  DspCosmics3 display;
  RcdEmcStageFix sfx;

  unsigned iEvent(0);
  while(reader->read(r)) {
    
    if(r.recordType()==RcdHeader::runStart) {
      sfx.record(r);
      display.event(r,en,false);
    }

    if(r.recordType()==RcdHeader::event) {
      cout << "Event = " << iEvent << endl;

      r2a.record(r,ad);
      //ad.print(cout);
      eg.event(ad,en);
      //en.print(cout);

      if(iEvent>100) {
	display.event(r,en,iEvent==psEvent); // true makes (e)ps file
	if(nSleep>0) sleep(nSleep);
      }

      pd.event(ad);
      iEvent++;
    }
  }

  reader->close();
  delete reader;

  return 0;
}
