#include <unistd.h>

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

#include "UtlArguments.hh"
#include "RcdArena.hh"
#include "RcdReaderBin.hh"
#include "RcdReaderAsc.hh"
#include "EmcMap.hh"
#include "EmcEventAdc.hh"
#include "EmcEventEnergy.hh"
#include "EmcPedestals.hh"
#include "RcdEmcRawToAdc.hh"
#include "EmcPedestals.hh"
#include "EmcEnergies.hh"
#include "HstHold_catherine.hh"
#include "SubAccessor.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;

  const unsigned nRuns(11);
  const unsigned runs[nRuns]={100100,100101,100102,100103,100104,100105,100106,100107,100108,100109,100110};
  //  const unsigned nRuns(1);
  //  const unsigned runs[nRuns]={100110};


  const bool useReadAsc(argh.option('a',"Ascii input file"));

  RcdReader *reader(0);
  if(useReadAsc) reader=new RcdReaderAsc();
  else           reader=new RcdReaderBin();

  //  if(!reader->open(std::string("data/dat/Run")+sout.str())) return 0;

  RcdArena r;

  HstHold_catherine hh(true);  
 
  EmcEventAdc ad;
  EmcEventEnergy en;
  EmcMap mp;
  EmcCalibration cl;
  //  assert(mp.read(std::string("data/map/Map")+sout.str()+".txt"));
  RcdEmcRawToAdc r2a(mp);
  EmcPedestals pd(cl);
  EmcEnergies eg(cl);
 
  SubAccessor extracter(r);
  
  unsigned count(0);

  ostringstream sout[nRuns];
  
  for(unsigned iRun(0);iRun<nRuns;iRun++) {
    
    sout[iRun] << runs[iRun];
    
    assert(reader->open(std::string("data/dat/Run")+sout[iRun].str()));
    
    assert(mp.read(std::string("data/map/Map")+sout[iRun].str()+".txt"));
    
    
    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++) {
	  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);
      }
      
      hh.record(r,en);
      
      count++;
      
    }
    
    reader->close();
    
  }
  
  std::ostringstream sout2;
  //  sout2 << "./data/sum/Run" << vnum << "_hold.ps";
  //  sout2 << "./plots/Run" << vnum << "_hold.ps";
  sout2 << "./Run" << sout[0] << "_" << sout[nRuns] << "_hold.ps";
  
  hh.update();
  hh.postscript(sout2.str());

  delete reader;
  return 0;
}

