#ifndef SlwWriter_HH
#define SlwWriter_HH

#include <cassert>

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


class SlwWriter : public RcdUserRO {

public:
  SlwWriter(bool d=false, bool a=false) : 
    RcdUserRO(), _writer(0), _startup(false) {

    if(d) {
      _writer=new RcdWriter();
    } else {
      if(a) _writer=new RcdWriterAsc();
      else  _writer=new RcdWriterBin();
    }
  }

  virtual ~SlwWriter() {
    delete _writer;
  }

  bool record(const RcdRecord &r) {

    bool openFile(false);

    if(r.recordType()==RcdHeader::startUp) {
      openFile=true;
      _startup=true;
    }

    if(r.recordType()==RcdHeader::slowStart) {
      if(_writer->isOpen()) {
	if(!_startup) {
	  openFile=true;
	  assert(_writer->close());
	}
      } else {
	openFile=true;
      }
      _startup=false;
    }

    if(openFile) {
      
      // Open output file
      std::ostringstream sout;
      sout << "data/slw/Slw" << time(0);
      
      assert(_writer->open(sout.str()));
    }

    assert(_writer->write(r));
    
    if(r.recordType()==RcdHeader::shutdown) {
      assert(_writer->close());
    }

    return true;
  }

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


private:
  RcdWriter *_writer;
  bool _startup;
};

#endif
