#include <unistd.h>

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

#include "UtlArguments.hh"
#include "RcdArena.hh"
#include "RcdReaderBin.hh"
//#include "RcdReaderAsc.hh"

#include "DspTestbeamView.hh"

#include "EmcMap.hh"
#include "EmcEventAdc.hh"
#include "EmcPedestals.hh"
#include "RcdEmcRawToAdc.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 unsigned vnum(argh.lastArgument(999999));
  std::ostringstream sout;
  sout << vnum;

  RcdReaderBin reader;
  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);
  
  DspTestbeamView display;
  
  double threshold = 30.;//ADC channels
  unsigned iEvent(0);
  
  
  //to display the layout and print it in viewLayout.gif
  //display.Layout(); 

  while(reader.read(r)) {
    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%50 == 0) 
      {
	
	display.event(r,en,threshold,vnum,iEvent);
	
	//to make files displayRunxxxEventxxx.eps and viewRunxxxEventxxx.gif 
	//display.event(r,en,threshold,vnum,iEvent,true); 
		
	sleep(0);
      }

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

  reader.close();
  return 0;
}
