#ifndef RunWriterData_HH
#define RunWriterData_HH

#include <cassert>

#include "DaqRunStart.hh"

#include "RcdUserRO.hh"
#include "RcdWriterDmy.hh"
#include "RcdWriterAsc.hh"
#include "RcdWriterBin.hh"

#include "SubAccessor.hh"


class RunWriterData : public RcdUserRO {

public:
  RunWriterData() : _writer(0) {
  }

  virtual ~RunWriterData() {
  }

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

    if(r.recordType()==RcdHeader::startUp) return true;
    if(r.recordType()==RcdHeader::shutDown) return true;

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

      // Check for no writer
      assert(_writer==0);

      // Access the DaqRunStart
      SubAccessor accessor(r);
      std::vector<const DaqRunStart*> v(accessor.access<DaqRunStart>());
      assert(v.size()==1);

      DaqRunType rt(v[0]->runType());
      if(rt.writeRun()) {
	if(rt.ascWriteRun()) _writer=new RcdWriterAsc;
	else                 _writer=new RcdWriterBin;
      } else {
	_writer=new RcdWriterDmy;
      }

      // Open data output file
      std::ostringstream dout;
      dout << "data/run/Run" << v[0]->runNumber();
      assert(_writer->open(dout.str()));
    }

    // Write out records
    assert(_writer->write(r));

    // Check for file size
    unsigned limit(2000000000);
    if(r.recordType()==RcdHeader::configurationEnd) limit=1700000000;
    if(r.recordType()==RcdHeader::acquisitionEnd  ) limit=1800000000;
    if(r.recordType()==RcdHeader::spillEnd        ) limit=1900000000;
    if(r.recordType()==RcdHeader::transferEnd     ) limit=1900000000;

    if(_writer->numberOfBytes()>limit) {
      if(doPrint(r.recordType())) std::cout << " Number of bytes written = "
					    << _writer->numberOfBytes()
					    << " > " << limit << std::endl;
      kill(getpid(),SIGUSR1);
    }
    
    if(r.recordType()==RcdHeader::runEnd) {

      // Check for writer
      assert(_writer!=0);

      // Close file and delete writer
      assert(_writer->close());
      delete _writer;
      _writer=0;
    }

    return true;
  }

  /*
  unsigned numberOfBytes() const {
    return _writer->numberOfBytes();
  }
  */

private:
  RcdWriter *_writer;
};

#endif
