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

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

#include "MpsAnalysis.hh"

using namespace std;


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

  // Get run number as last (=only) argument
  UtlArguments argh(argc,argv);
  const unsigned numberOfBtrs(argh.optionArgument('b',1000000000,"Number of bunch trains"));
  const unsigned numberOfCfgs(argh.optionArgument('c',1000000000,"Number of configurations"));
  const unsigned numberOfRuns(argh.optionArgument('n',1,"Number of runs"));
  const unsigned runnum(argh.lastArgument(999999));

  if(argh.help()) return 0;

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

  // Define memory space for records
  RcdArena arena;

  // Create simple record type counter and configuration counter
  RcdCount counter;
  unsigned nCfg(0);
  unsigned nBtr(0);

  // Create MAPS analysis module
  MpsAnalysis analysis;
  
  // This can handle both single-file and multi-file runs
  RunReader reader;

  for(unsigned run(0);run<numberOfRuns;run++) {

    // Open run file using reader
    assert(reader.open(runnum+run));

    // Loop over all records until end-of-file
    while(reader.read(arena) && nCfg<numberOfCfgs && nBtr<numberOfBtrs) {

      // Increment counters
      counter+=arena;
      if(arena.recordType()==RcdHeader::bunchTrain) nBtr++;
      if(arena.recordType()==RcdHeader::configurationEnd) nCfg++;

      // Run analysis
      analysis.record(arena);
    }
    
    // Close run file
    assert(reader.close());
  }
    
  // Print total of counts
  cout << endl;
  counter.print(cout);

  return 0;
}
