#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
#include <fcntl.h>
#include <unistd.h>

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

#include "UtlTime.hh"
#include "UtlArguments.hh"
#include "RcdArena.hh"
#include "DaqRunStart.hh"
#include "RcdReaderAsc.hh"
#include "RcdReaderBin.hh"
#include "RunReader.hh"

#include "SubAccessor.hh"

#include "HstBattery.hh"

using namespace std;

bool continueJob=true;

void signalHandler(int signal) {
  std::cout << "Process " << getpid() << " received signal "
	    << signal << std::endl;
  continueJob=false;
}

int main(int argc, const char **argv) {
  UtlArguments argh(argc,argv);
  //argh.print(cout);

  bool doGraphics(true);
  //include "arguments.icc"

  const unsigned slot(argh.optionArgument('s',12,"Slot"));

  const unsigned vnum(argh.lastArgument(999999));
  ostringstream sout;
  sout << vnum;

  RcdArena arena;
  //RcdReaderBin reader;
  RunReader reader;

  HstBattery *hn(0);
  if(doGraphics) hn=new HstBattery(slot);

  //reader.open("dat/Run1099819725"); // SER003
  //reader.open("dat/Run1099840335"); // SER001
  //reader.open("dat/Run1099915737"); // SER004

  unsigned x(0);

  reader.open(vnum);
  while(reader.read(arena)) {
    if((x%1000)==0) std::cout << "Record " << x << std::endl;
    x++;
    if(hn!=0) hn->record(arena);
  }
  reader.close();

  /*
  reader.open(std::string("data/run/Run")+sout.str()+".000");
  while(reader.read(arena)) {
    if((x%1000)==0) std::cout << "Record " << x << std::endl;
    x++;
    if(hn!=0) hn->record(arena);
  }
  reader.close();

  reader.open(std::string("data/run/Run")+sout.str()+".001");
  while(reader.read(arena)) {
    if((x%1000)==0) std::cout << "Record " << x << std::endl;
    x++;
    if(hn!=0) hn->record(arena);
  }
  reader.close();
  */

  //if(hn!=0) hn->postscript("dps/Run1099819725.ps");
  //if(hn!=0) hn->postscript("dps/Run1099840335.ps");
  //if(hn!=0) hn->postscript("dps/Run1099915737.ps");

  if(slot<10) sout << "Slot0" << slot << ".ps";
  else        sout << "Slot"  << slot << ".ps";
  if(hn!=0) hn->postscript(std::string("Run")+sout.str());
  if(hn!=0) delete hn;
}
