#include "runnerDefine.icc"

#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 numberOfRuns(argh.optionArgument('n',1,"Number of runs"));
  const unsigned runnum(argh.lastArgument(999999,"Run number"));

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

  if(argh.help()) return 0;

  // Define memory space for records
  RcdArena arena;
  RcdHeader lastHeader;

  // This can handle both single-file and multi-file runs
  RunReader reader;
  bool runExists(true);

  for(unsigned n(0);n<numberOfRuns && runExists;n++) {

    // Open run file using reader
    runExists=reader.open(runnum+n);
    if(runExists) {

      // Open output file
      std::ostringstream sout;
      sout << "data/sum/Run" << std::setfill('0') << std::setw(6) << runnum+n << ".txt";
      std::ofstream fout(sout.str().c_str());
      if(fout) {
	
	// 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(fout) << 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
#ifndef DAQ_ILC_TIMING
	    std::vector<const DaqRunStart*>
	      vs(accessor.access<DaqRunStart>());
#else
	    std::vector<const IlcRunStart*>
	      vs(accessor.access<IlcRunStart>());
#endif
	    for(unsigned i(0);i<vs.size();i++) {
	      vs[i]->print(fout) << std::endl;
	    }
	    
	    // Get list of DaqRunEnd subrecords
	    // There should only be one and it should only
	    // be in the runEnd record
#ifndef DAQ_ILC_TIMING
	    std::vector<const DaqRunEnd*>
	      ve(accessor.access<DaqRunEnd>());
#else
	    std::vector<const IlcRunEnd*>
	      ve(accessor.access<IlcRunEnd>());
#endif
	    for(unsigned i(0);i<ve.size();i++) {
	      ve[i]->print(fout) << std::endl;
	    }
	  }

	  // Remember last header
	  lastHeader=arena;
	}

	if(lastHeader.recordType()!=RcdHeader::runEnd) {
	  lastHeader.print(fout) << endl;
	}
	
	// Print total of counts
	cout << endl;
	counter.print(fout);
	
	// Make file read-only
	system(std::string("chmod 444 "+sout.str()).c_str());
	
      } else {
	std::cout << sout.str() << " cannot be opened; already exists?" << std::endl;
      }
      
      // Close run file
      assert(reader.close());
    }
  }

  return 0;
}
