#include "RcdArena.hh"
#include "RcdReaderBin.hh"
#include "RcdReaderAsc.hh"
#include "RcdWriterBin.hh"
#include "FixAll.hh"

using namespace std;

int main(int argc, const char **argv) {
  if(argc<2 || argc>3) {
    cout << "Usage: " << argv[0] 
    	 << " <input filename> [<output filename>]" << endl;
    return 1;
  }

  // Memory array for records
  RcdArena arena;

  // Record reader; run, bin or asc
  RcdReaderBin reader;
  //RcdReaderAsc reader;

  // Record writer if required
  RcdWriter *writer(0);
  if(argc==3) writer=new RcdWriterBin;

  // Fixers to repair data
  FixAll fixAll(4); // 4 prints up to and including configuration
  
  // Open files
  if(!reader.open(argv[1])) return 2;
  if(argc==3 && !writer->open(argv[2])) return 3;

  // Read records until end of file
  while(reader.read(arena)) {
    fixAll.fix(arena);
    if(argc==3) writer->write(arena);
  }

  // Close files
  if(!reader.close()) return 4;
  if(argc==3 && !writer->close()) return 5;

  return 0;
}
