#include <unistd.h>

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

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

  RcdReaderAsc 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);
  DspCosmics3 display;

  SubAccessor extracter(r);

  unsigned iEvent(0);
  while(reader.read(r)) {
    if (r.recordType()==RcdHeader::configurationStart) {
      std::vector<const CrcLocationData<CrcBeTrgConfigurationData>*>
        bt(extracter.extract< CrcLocationData<CrcBeTrgConfigurationData> >());


      for(std::vector<const CrcLocationData<CrcBeTrgConfigurationData>*>::iterator bt_iter=bt.begin();
	  bt_iter!=bt.end(); 
	  bt_iter++) {
	//	cout << "trigger=" << (*bt_iter)->data()->inputEnable() << endl;
	if ((*bt_iter)->data()->inputEnable() == 1<<0) {
	  cout << "Recalculate pedestals" << endl;
	  pd.calculate();
	}
	else if ((*bt_iter)->data()->inputEnable() == 1<<24) {
	  cout << "Reset pedestals" << endl;
	  pd.reset();
	  break;
	}
      }

      //      if (bt.size()>0) {
      //	cout << "type=" << r.recordType() << " n_confs=" << bt.size()<< endl;
      //	extracter.print(std::cout,"");
      //      }
    }

    else 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);
	//display.event(r,en,true); // make (e)ps file
	sleep(1);
      }

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

  reader.close();
  return 0;
}
