#ifndef HstEvent_HH
#define HstEvent_HH

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

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

#include "UtlAverage.hh"
#include "RcdRecord.hh"
#include "EmcCercFeEventData.hh"
#include "HodData.hh"
#include "HodTrack.hh"
#include "DaqEvent.hh"
#include "SubExtracter.hh"


class HstEvent {

public:
  HstEvent(unsigned n=100) : _application("Noise Application",0,0),
			     _canvas("Noise Canvas","Noise Canvas",500,10,600,800),
			     _nEvents(n) {

    gROOT->Reset();
    gROOT->SetStyle("Plain");
    _canvas.Divide(1,2);

    _graph[0].Set(216);
    _graph[0].SetTitle("Pedestal vs Chip/Channel");
    _graph[0].SetMarkerColor(1);
    _graph[0].SetMarkerStyle(20);

    _graph[1].Set(216);
    _graph[1].SetTitle("Noise vs Chip/Channel");
    _graph[1].SetMarkerColor(1);
    _graph[1].SetMarkerStyle(20);
  }

  virtual ~HstEvent() {
  }

  void update(bool ps=false) {
    std::cout << "Updating..." << std::endl;

    for(unsigned chan(0);chan<18;chan++) {
      for(unsigned chip(0);chip<12;chip++) {
	unsigned bin(18*chip+chan);
	_graph[0].SetPoint(bin,bin,_average[chip][chan].average());
	_graph[0].SetPointError(bin,0.0,_average[chip][chan].errorOnAverage());
	_graph[1].SetPoint(bin,bin,_average[chip][chan].sigma());
	_graph[1].SetPointError(bin,0.0,_average[chip][chan].errorOnSigma());
	_average[chip][chan].reset();
      }
    }

    _canvas.Clear("D");

    _canvas.cd(1);
    _graph[0].Draw("AP");
    _canvas.cd(2);
    _graph[1].Draw("AP");
    _canvas.Update();

    if(ps) _canvas.Print("dps/noise.ps");
  }

  void event(RcdRecord &r) {
    if(r.recordType()!=SubHeader::event) return;
    
    SubExtracter extracter(r);
    
    std::vector<const DaqEvent*> z(extracter.extract<DaqEvent>());
    assert(z.size()==1);

    //if((z[0]->eventNumberInConfiguration()%_nEvents)==0) update();

    std::vector<const EmcCercFeEventData*> v(extracter.extract<EmcCercFeEventData>());

    for(unsigned i(0);i<v.size();i++) {
      if(v[i]->feNumber()==0) {
	for(unsigned chan(0);chan<v[i]->numberOfSamples() && chan<18;chan++) {
	  for(unsigned chip(0);chip<12;chip++) {
	    _average[chip][chan].event(v[i]->adc(chip,chan));
	  }
	}
      }
    }
  }

private:
  TApplication _application;
  TCanvas _canvas;
  TGraphErrors _graph[2];
  UtlAverage _average[12][18];
  unsigned _nEvents;
};

#endif
