#ifndef HstTFile_HH
#define HstTFile_HH

#include "TROOT.h"
#include "TApplication.h"
#include "TFile.h"

#include "RcdUserRO.hh"


class HstTFile : public RcdUserRO {

public:
  HstTFile(const std::string &f, bool r=true, bool i=true) :
    _updatePeriod(0), _numberOfRecords(0) {

    if(!r) _file=TFile::Open(f.c_str(),"CREATE");
    else   _file=TFile::Open(f.c_str(),"RECREATE");

    if(!_file) {
      std::cerr << "Cannot open ROOT file " << f << std::endl;
      assert(false);
    }
 
    if(i) {
      _application=new TApplication("HstBase Application",0,0);
      gROOT->Reset();
    } else {
      _application=0;
    }
 
    gROOT->SetStyle("Plain");
  }
  
  virtual ~HstTFile() {
    std::cout << "In HstTFile::dtor()" << std::endl;
    //_file->Write();
    _file->Close();
    delete _file;
    delete _application;
  }

  bool record(const RcdRecord &r) {
    if(_updatePeriod>0 && (_numberOfRecords%_updatePeriod)==0) _file->Write();
    if(r.recordType()==RcdHeader::runEnd) _file->Write();
    _numberOfRecords++;
    return true;
  }

  void write() {
    _file->Write();
  }
  
private:
  TApplication *_application;
  TFile *_file;
  unsigned _updatePeriod;
  unsigned _numberOfRecords;
};

#endif
