#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(1);
  const unsigned runs[nRuns]={100001};
  //    1106002056,1106022608};

  //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);

  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;
	}
      }
    }
    else if(r.recordType()==RcdHeader::event) {
      r2a.record(r,ad);
      eg.event(ad,en);
      pd.event(ad);
    }

    //if(count>100) {
      hst.record(r,en);
      //}
      //count++;
  }
  iEvent++;
  hst.pos/localstage/home/calice/software/daqMain/tscript("cosmicScan_pedupdate_100001.ps");

  reader.close();
  return 0;
}
/localstage/home/calice/software/daqMain/
