#ifndef RunWriter_HH
#define RunWriter_HH

#include <sstream>
#include <fstream>
#include <iostream>

// dual/inc/rcd
#include "RcdUserRO.hh"
#include "RcdWriterAsc.hh"
#include "RcdWriterBin.hh"
#include "RcdWriterDmy.hh"

// dual/inc/sub
#include "SubAccessor.hh"

// dual/inc/daq
#include "DaqRunStart.hh"


class RunWriter : public RcdUserRO {

public:
  RunWriter() : RcdUserRO(), _writer(0), _startUp(0) {
  }

  virtual ~RunWriter() {
    delete _writer;
  }

  bool record(const RcdRecord &r) {

    // Run start 
    if(r.recordType()==RcdHeader::runStart) {
      

    // Run start 
    if(r.recordType()==RcdHeader::runStart) {
      
      // Access the DaqRunStart
      SubAccessor accessor(r);
      std::vector<const DaqRunStart*> v(accessor.extract<DaqRunStart>());
      assert(v.size()==1);
      
      // Open output file
      std::ostringstream sout;
      sout << "data/dat/Run" << v[0]->runNumber();

      assert(_writer->open(sout.str()));
    }

    if(_writer->isOpen()) assert(_writer->write(r));
    
    if(r.recordType()==RcdHeader::runStop ||
       r.recordType()==RcdHeader::runEnd) {

      assert(_writer->close());
    }

    return true;
  }


private:
  RcdWriter *_writer;
  RcdArena *_startUp;
};

#endif
