#ifndef HstSpill_HH
#define HstSpill_HH

#include <cassert>

#include "TMapFile.h"
#include "TH1F.h"

#include "RcdUserRO.hh"


class HstSpill : public RcdUserRO {

public:
  HstSpill() {

    _hstSpillTime=new TH1F("HstSpillTime",
			   "Spill length",
			   100,0.0,0.2);
    _hstSpillTrg=new TH1F("HstSpillTrg",
			   "Spill distribution of triggers (secs)",
			   100,-0.25,0.25);
    _hstSpillPre=new TH1F("HstSpillPre",
			  "Number of triggers before spill",
			  50,0,50);
    _hstSpillPost=new TH1F("HstSpillPost",
			   "Number of triggers after spill",
			   50,0,50);
      _inSpill=false;
  }

  virtual ~HstSpill() {
    delete _hstSpillTime;
    delete _hstSpillTrg;
    delete _hstSpillPre;
    delete _hstSpillPost;
  }


  bool record(const RcdRecord &r) {
    if(doPrint(r.recordType())) {
      std::cout << "HstSpill::record()" << std::endl;
      r.RcdHeader::print(std::cout," ") <<std::endl;
    }

    //if(r.recordType()==RcdHeader::runStart) {
    if(r.recordType()==RcdHeader::configurationStart) {

      // Reset all hists
      _hstSpillTime->Reset();
      _hstSpillTrg->Reset();
      _hstSpillPre->Reset();
      _hstSpillPost->Reset();

      return true;
    }

    /*

    if(r.recordType()==RcdHeader::configurationStart) {
      _trgPoll[0][2]->Reset();
      _trgPoll[1][2]->Reset();
      _trgProc[0][2]->Reset();
      _trgProc[1][2]->Reset();
      return true;
    }
    */

    /*
    if(r.recordType()==RcdHeader::spillStart) {
      _spillStartTime=_vTime[_vTime.size()-1];

      _hstSpillPre->Fill(_vTime.size()-1);
      for(unsigned i(0);i<_vTime.size();i++) {
	double dt((_spillStartTime-_vTime[i]).deltaTime());
	_hstSpillTrg->Fill(-dt);
      }

      _inSpill=true;
      _nPost=1; // Include trigger which started spill
      _sinceSpillStart=0.0;
      return true;
    }

    if(r.recordType()==RcdHeader::spillEnd) {
      _hstSpillTime->Fill(_sinceSpillStart);
      _hstSpillPost->Fill(_nPost);
      _inSpill=false;
      _vTime.clear();
    }


    if(r.recordType()==RcdHeader::trigger) {

      UtlTime t(r.recordTime());

      SubAccessor accessor(r);
      std::vector<const CrcLocationData<CrcBeTrgPollData>* >
        v(accessor.access< CrcLocationData<CrcBeTrgPollData> >());
      if(v.size()>0) t+=v[0]->data()->actualTime();

      if(_inSpill) {
	_nPost++;
	_sinceSpillStart=(t-_spillStartTime).deltaTime();
	_hstSpillTrg->Fill(_sinceSpillStart);
      } else {
	_vTime.push_back(t);
      }
      return true;
    }
    */

    return true;
  }

private:
  TH1F *_hstSpillTime;
  TH1F *_hstSpillTrg;
  TH1F *_hstSpillPre;
  TH1F *_hstSpillPost;

  unsigned _nPost;
  bool _inSpill;
  UtlTime _spillStartTime;
  std::vector<UtlTime> _vTime;
  double _sinceSpillStart;
};

#endif
