//#include <sys/types.h>
//#include <sys/stat.h>
//#include <signal.h>
//#include <fcntl.h>
//#include <unistd.h>

#include <iostream>
#include <sstream>
#include <vector>
//#include <cstdio>

//#include "UtlTime.hh"
#include "UtlArguments.hh"
#include "RcdArena.hh"
#include "RcdReaderBin.hh"
#include "RunReader.hh"
#include "SubAccessor.hh"

using namespace std;

bool newRun;
RcdHeader runHeader;

void doPrint(const RcdRecord &arena) {
  if(arena.recordType()==RcdHeader::runStart) {
    newRun=true;
    runHeader=arena;
  }

  SubAccessor accessor(arena);

  std::vector<const CrcLocationData<AhcVfeStartUpData>*>
    v(accessor.access<CrcLocationData<AhcVfeStartUpData> >());

  if(v.size()>0) {
    if(newRun) {
      newRun=false;
      runHeader.print(std::cout) << std::endl;
    }

    arena.RcdHeader::print(std::cout) << std::endl;
    
    for(unsigned i(0);i<v.size();i++) {
      v[i]->print(std::cout," ") << std::endl;
    }
  }

  if(arena.recordType()==RcdHeader::runEnd) newRun=false;
}

int main(int argc, const char **argv) {
  UtlArguments argh(argc,argv);
  const unsigned vnum(argh.lastArgument(999999));

  RcdArena arena;
  newRun=false;

  // Is is a run number or Unix epoch time?
  if(vnum>999999) {
    RcdReaderBin reader;

    std::ostringstream sout;
    sout << "data/slw/Slw" << vnum;

    assert(reader.open(sout.str()));
    while(reader.read(arena)) doPrint(arena);
    assert(reader.close());

  } else {
    RunReader reader;
    assert(reader.open(vnum));
    while(reader.read(arena)) doPrint(arena);
    assert(reader.close());
  }

  return 0;
}
