#ifndef HstEventRate_HH
#define HstEventRate_HH

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

#include "TROOT.h"
#include "TApplication.h"
#include "TCanvas.h"
#include "TH1D.h"
#include "TGraphErrors.h"
#include "TPostScript.h"

#include "UtlAverage.hh"
#include "RcdRecord.hh"
#include "CrcFeEventData.hh"
#include "CrcLocationData.hh"
#include "DaqEvent.hh"
#include "HstBase.hh"
#include "HstTGraph.hh"
#include "SubAccessor.hh"


class HstEventRate : public HstBase {

public:
  HstEventRate(bool i=true) : 
    HstBase(i), _firstRecordTime(0), _timeBinEdge(0), _eventCount(0) {
    ostringstream sout;
    sout << "EventRateCanvas";
    _canvas=new TCanvas(sout.str().c_str(),"Event rate",400,20,600,400);
  }
  
  virtual ~HstEventRate() {
  }

  
  bool record(const RcdRecord &r) {

    if(_firstRecordTime==0) {
      _firstRecordTime=r.recordTime().seconds();
      _graph.SetTitle("Event rate / Hz against time since run start / min");
      _graph.SetMarkerColor(2);
      _graph.SetMarkerStyle(22);

    }

    double deltat(r.recordTime().seconds()-_firstRecordTime);
    
    if(r.recordType()==RcdHeader::event){
      if((deltat-_timeBinEdge)<300) {
	_eventCount++;
      }
      else{
	_graph.AddPoint(((_timeBinEdge+150)/60.0),(_eventCount/300.0));
	_eventCount=0.0;
	_timeBinEdge+=300;
      }
    }

    return true;
  }

  
  bool update() {
    _canvas->Clear();
    _graph.Draw("AP");
    _canvas->Update();
    return true;
  }

  bool postscript(std::string file) {
    std::cout << "HstEventRate::postscript()  Writing to file "
              << file << std::endl;

    TPostScript ps(file.c_str(),112);
    update();
    ps.Close();

    return true;
  }

private:
  unsigned _firstRecordTime;
  double _timeBinEdge;
  double _eventCount;
  TCanvas *_canvas;
  HstTGraph _graph;
};

#endif
