#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 two arguments
  UtlArguments argh(argc,argv);
  const unsigned runLo(argh.argument(0,999999));
  const unsigned runHi(argh.argument(1,999999));

  if(runLo==999999 || runHi==999999) {
    cout << "Usage: " << argv[0] << " <low run number> <high run number>" << endl;
    return 1;
  }

  // Define memory space for records
  RcdArena arena;

  // Define reader to use
  RunReader reader;

  // Output file
  std::ofstream fout("AllRunTypes.txt");

  for(unsigned runnum(runLo);runnum<=runHi;runnum++) {

    // Open run file using reader
    if(reader.open(runnum)) {

      // Read first record
      if(reader.read(arena)) {

	// Select to look at run start and end records
	if(arena.recordType()==RcdHeader::runStart) {
	  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;
	  }

	  if(vs.size()==1) {
	    DaqRunType rt(vs[0]->runType());
	    fout << "Run " << std::setw(6) << runnum
		 << ", Type " << rt.typeName() << std::endl;
	  }

	} else {
	  std::cerr << "runStart not found!!!" << std::endl;
	}
      }
      
      // Close run file
      assert(reader.close());
    }
  }

  return 0;
}
