#include <iostream>
#include <sstream>
#include <vector>

#include "UtlArguments.hh"
#include "RcdArena.hh"
#include "RcdCount.hh"
#include "RunReader.hh"
#include "SubAccessor.hh"

using namespace std;


int main(int argc, const char **argv) {

  // Get run number as last (=only) argument
  UtlArguments argh(argc,argv);
  const unsigned runnum(argh.lastArgument(999999));

  if(runnum==999999) {
    cout << "Usage: " << argv[0] << " <run number>" << endl;
    return 1;
  }

  // Define memory space for records
  RcdArena arena;

  // Open run file using reader
  // This can handle both single-file and multi-file runs
  RunReader reader;
  assert(reader.open(runnum));

  // Create simple record type counter
  RcdCount counter;

  // Loop over all records until end-of-file
  while(reader.read(arena)) {

    // Increment counter
    counter+=arena;

    // Select to look at run start and end records
    if(arena.recordType()==RcdHeader::runStart ||
       arena.recordType()==RcdHeader::runEnd) {
      arena.RcdHeader::print(cout) << endl;

      // Now access some of the subrecords in the file
      SubAccessor accessor(arena);    

      // Get list of DaqRunStart subrecords
      // There should only be one and it should only
      // be in the runStart record
      std::vector<const DaqRunStart*>
	vs(accessor.access<DaqRunStart>());
      for(unsigned i(0);i<vs.size();i++) {
        vs[i]->print(cout) << std::endl;
      }

      // Get list of DaqRunEnd subrecords
      // There should only be one and it should only
      // be in the runEnd record
      std::vector<const DaqRunEnd*>
        ve(accessor.access<DaqRunEnd>());
      for(unsigned i(0);i<ve.size();i++) {
        ve[i]->print(cout) << std::endl;
      }
    }
  }

  // Close run file
  assert(reader.close());

  // Print total of counts
  cout << endl;
  counter.print(cout);

  return 0;
}
