#include <signal.h>
#include <iostream>

#include "RcdArena.hh"
#include "RcdRecord.hh"
#include "RcdHeader.hh"
#include "RcdReaderBin.hh"
#include "SubAccessor.hh"

#include "UtlArguments.hh"
#include "UtlTime.hh"

#include "TROOT.h"
#include "TTree.h"
#include "TFile.h"

using namespace std;

bool continueJob=true;

void signalHandler(int signal) {
  std::cout << "Process " << getpid() << " received signal "
	    << signal << std::endl;
  continueJob=false;
}

struct myEvent_t {
  Int_t time[2];
  Short_t ADC[22][8][12][18];
};

#define myEvent_format "time[2]/I:ADC[22][8][12][18]/S"


int main(int argc, const char **argv) {
  UtlArguments argh(argc,argv);

  const unsigned slot(argh.optionArgument('s',0,"Slot"));
  const unsigned Nevent(argh.optionArgument('N',500,"No. of events between updates of screen"));
  // const unsigned selectedFE(argh.optionArgument('F',8,"frontend - needed for some histograms"));
  //  const unsigned selectedChip(argh.optionArgument('C',8,"chip - needed for some histograms"));
  const unsigned vnum(argh.lastArgument(999999));


  argh.print(cout,"*");

  ostringstream sout;
  sout << vnum;

  RcdReaderBin reader;
  RcdArena arena;


  reader.open(string("data/run/Run")+sout.str()+string(".000"));
  TFile *rootFile = new TFile((string("Run")+sout.str()+"_tree.root").c_str(),"NEW");
  if (!rootFile->IsOpen()) exit(1);
  ostringstream treeName;

 
  myEvent_t event;
  treeName <<"FullCrate_tree" ;
  TTree *tree = new TTree(treeName.str().c_str(),treeName.str().c_str());
  tree->Branch("events",&event.time[0],myEvent_format);
     

  unsigned counter(0);

  while (reader.read(arena)) {

    if (arena.recordType()==RcdHeader::event){

      SubAccessor extracter(arena);
      std::vector<const CrcLocationData<CrcVlinkEventData>* > v(extracter.extract< CrcLocationData<CrcVlinkEventData> >());

      event.time[0]= arena.recordTime().seconds();
      event.time[1]= arena.recordTime().microseconds();
      for(unsigned i(0);i<v.size();i++) {
	if(v[i]->slotNumber()==slot || slot==0 ) {
	  for(unsigned fe(0);fe<8;fe++) {
	    const CrcVlinkFeData *fd(v[i]->data()->feData(fe));
	    if(fd!=0) {
	      for(unsigned chan(0);chan<v[i]->data()->feNumberOfAdcSamples(fe) && chan<18;chan++) {
		const CrcVlinkAdcSample *as(fd->adcSample(chan));
		if(as!=0) {
		    for(unsigned chip(0);chip<12;chip++) {
		      event.ADC[v[i]->slotNumber()][fe][chip][chan] = as->adc(chip);
		    }
		}
	      }
	    }
	  }
	}
      }
    

      if (++counter%Nevent==0) {
	//	hn->update();
	cout << counter << endl;
	//	hn->postscript("bla");
      }

      tree->Fill();

    }


      
  }
    
  rootFile->Write();
  rootFile->Close();
  delete rootFile;


}
