#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
#include <fcntl.h>
#include <unistd.h>

#include <iostream>
#include <sstream>
#include <vector>
#include <cstdio>

#include "UtlTime.hh"
#include "UtlArguments.hh"
#include "RcdArena.hh"
#include "RcdWriterAsc.hh"

#include "DaqRunStart.hh"
#include "RcdReaderAsc.hh"

#include "ChkCount.hh"
#include "LcoEmcConverter.hh"
#include "RcdEmcRawToAdc.hh"
#include "EmcEventAdc.hh"

using namespace std;


int main(int argc, const char **argv) {
  UtlArguments argh(argc,argv);
  //argh.print(cout);

  const unsigned vnum(argh.lastArgument(999999));
  ostringstream sout;
  sout << vnum;

  RcdArena arena;
  RcdReaderAsc reader;
  ChkCount hn;

  EmcMap map;
  //map.print(cout);
  EmcCalibration cal;
  assert(cal.read(std::string("cal/Cal")+sout.str()+".txt"));
  //cal.print(cout);
  EmcAlignment ali;
  //ali.print(cout);

  EmcEventAdc adc;
  RcdEmcRawToAdc r2a(map);
  LcoEmcConverter a2l(cal,ali);

  std::ofstream fout((std::string("dat/Run")+sout.str()+".lcio").c_str());

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

  while(reader.read(arena)) {
    hn.record(arena);
    if(arena.recordType()==RcdHeader::event) {
      r2a.event(arena,adc);
      a2l.event(adc,fout);
    }
  }
  hn.print(cout);

  fout.close();
  reader.close();
}
