#ifndef HstSlwMonLm82_HH
#define HstSlwMonLm82_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"
#include "HstBase.hh"
#include "HstTGraph.hh"


class HstSlwMonLm82 : public HstBase {

public:
  HstSlwMonLm82(CercLocationData d, bool i=true) : 
    HstBase(i), _cld(d), _firstRecordTime(0) {

    _canvas[0]=new TCanvas("Canvas[0]","Canvas[0]",400,20,600,400);
    _canvas[1]=new TCanvas("Canvas[1]","Canvas[1]",420,40,600,400);
    _canvas[2]=new TCanvas("Canvas[2]","Canvas[2]",440,60,600,400);

  }

  virtual ~HstSlwMonLm82() {
  }

  bool record(const RcdRecord &r) {
    if(r.recordType()!=SubHeader::startUp &&
       r.recordType()!=SubHeader::slowControl) return true;

    if(_firstRecordTime==0) {
      _firstRecordTime=r.recordTime().seconds();

      for(unsigned i(0);i<3;i++) {
	ostringstream sout;
	sout << "Crate " << (unsigned)_cld.crateNumber() << ", Slot " 
	     << (unsigned)_cld.slotNumber() << ", CERC " 
	     << _cld.cercComponentName() << " LM82 ";
	
	if(i==0) sout << "Local Temperature";
	if(i==1) sout << "Remote Temperature";
	if(i==2) sout << "Status";

	sout << " vs Time (Days) since " << r.recordTime();

	_graph[i].SetTitle(sout.str().c_str());
	_graph[i].SetMarkerColor(1);
	_graph[i].SetMarkerStyle(20);
      }
    }

    double deltat((r.recordTime().seconds()-_firstRecordTime)/(24.0*3600.0));

    SubExtracter extracter(r);

    if(r.recordType()==SubHeader::startUp) {
      std::vector<const SlwCercLm82StartupData*>
        c(extracter.extract<SlwCercLm82StartupData>());
      assert(c.size()==1);

      if(printLevel()>0) c[0]->print(std::cout);
      
      return true;
    }

    std::vector<const SlwCercLm82SlowControlsData*>
      c(extracter.extract<SlwCercLm82SlowControlsData>());
    assert(c.size()==1);

    if(printLevel()>2) c[0]->print(std::cout);
      
    _graph[0].AddPoint(deltat,c[0]->localTemperature());
    _graph[1].AddPoint(deltat,c[0]->remoteTemperature());
    _graph[2].AddPoint(deltat,c[0]->status());

    return true;
  }

  bool update() {
    for(unsigned i(0);i<3;i++) {
      _canvas[i]->Clear();
      _graph[i].Draw("AP");
      _canvas[i]->Update();
    }

    return true;
  }

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

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

    return true;
  }

private:
  CercLocationData _cld;
  unsigned _firstRecordTime;
  TCanvas *_canvas[3];
  HstTGraph _graph[3];
};

#endif
