#include <unistd.h>

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

#include "UtlArguments.hh"
#include "RcdArena.hh"
#include "RcdReaderAsc.hh"
#include "HstCosmicScan.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);

  //  unsigned vnum(1102703739);

  // cosmicsDec04 scan
  //const unsigned nRuns(1);
  //const unsigned runs[nRuns]={1102703739};

  // beamScan Jan05
  //  const unsigned nRuns(2);
  //const unsigned runs[nRuns]={1106002056,1106022608};

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

  //unsigned vnum(1103324633);
  //const unsigned vnum(argh.lastArgument(999999));
  ostringstream sout;
  sout << runs[0];

  RcdReaderAsc reader;
  if(!reader.open(std::string("data/dat/Run")+sout.str())) return 0;
  //if(!reader.open("dat/Run1103324633")) 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);
  HstCosmicScan hst(0xffff,0.0,0.0,false);

  unsigned count(0);
  while(reader.read(r)) {// && count<2000) {
    //cout << "Counter = " << count << endl;

    if(r.recordType()==RcdHeader::event) {
      r2a.record(r,ad);
      eg.event(ad,en);
      pd.event(ad);
    }

    //if(count>100) {
      hst.record(r,en);
      //}
    count++;
  }

  hst.postscript("cosmicScan_100001.ps");

  reader.close();
  return 0;
}
