#include "runnerDefine.icc"

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

#include <iostream>

#include "ShmObject.hh"
#include "RunMonitorShm.hh"
#include "UtlArguments.hh"

using namespace std;

bool continueJob=true;

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


int main(int argc, const char *argv[]) {
  UtlArguments argh(argc,argv);
  const unsigned version(argh.optionArgument('v',0,"Display format"));
  const bool jamie(argh.option('j',false,"Jamie output"));
  if(argh.help()) return 0;

  signal(SIGINT,signalHandler);
  signal(SIGTERM,signalHandler);

  ShmObject<RunMonitorShm> shmRunMonitor(RunMonitorShm::shmKey);
  RunMonitorShm *q(shmRunMonitor.payload());
  if(q==0) return 1;

#ifndef DAQ_ILC_TIMING
  DaqRunStart *p(&(q->runStart()));
#else
  IlcRunStart *p(&(q->runStart()));
#endif
  if(p==0) return 2;

  if(!jamie) {
    if(version==1) {
      std::cout << "Run number " << p->runNumber() << std::endl;
    } else {
      p->print(std::cout);
    }
  } else {

#ifndef DAQ_ILC_TIMING
    if(p->runType().type()==DaqRunType::daqTest) std::cout << 0 << std::endl;
    else if(p->runType().type()==DaqRunType::slowMonitor) std::cout << 1 << std::endl;
#else
    if(p->runType().type()==IlcRunType::daqTest) std::cout << 0 << std::endl;
    else if(p->runType().type()==IlcRunType::slwMonitor) std::cout << 1 << std::endl;
#endif
    else if(!p->runType().writeRun()) std::cout << 2 << std::endl;
    else std::cout << p->runNumber() << std::endl;
  }

  return 0;
}
