#include <iostream>
#include <sstream>

#include "UtlArguments.hh"
#include "RcdArena.hh"
#include "RcdReaderSkt.hh"
#include "RcdWriterBin.hh"
#include "SubAccessor.hh"

using namespace std;

int main(int argc, const char **argv) {
  UtlArguments argh(argc,argv);
  argh.print(cout);
  const unsigned runNumber(argh.lastArgument(999999));
  
  RcdArena arena;
  RcdReaderSkt reader;
  RcdWriterBin writer;

  reader.open("localhost");
  //reader.open("131.169.61.122");

  while(reader.read(arena)) {
    if(arena.recordType()==RcdHeader::runStart) {
      SubAccessor accessor(arena);
      std::vector<const DaqRunStart*> v(accessor.extract<DaqRunStart>());
      assert(v.size()==1);

      ostringstream sout;
      //sout << "data/slw/Run" << v[0]->runNumber();
      sout << "data/slw/Run" << runNumber;

      assert(writer.open(sout.str()));
    }

    assert(writer.write(arena));

    if(arena.recordType()==RcdHeader::runStop ||
       arena.recordType()==RcdHeader::runEnd) {
      assert(writer.close());
    }
  }

  reader.close();
}
