#include "runnerDefine.icc"

#include <iostream>
#include <unistd.h>

#include "RcdArena.hh"
#include "SubInserter.hh"
#include "UtlArguments.hh"

#include "MpsReadout.hh"

using namespace std;


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

  UtlArguments argh(argc,argv);
  const unsigned nCfg(argh.optionArgument('c',2,"Number of configurations"));
  const unsigned nBnt(argh.optionArgument('b',10,"Number of bunch trains per configuration"));
  const unsigned printLevel(argh.optionArgument('p',255,"Print level"));
  if(argh.help()) return 0;

  MpsReadout asr(MPS_LOCATION,1);
  asr.printLevel(printLevel);

  MpsLocation location;
  location.siteNumber(MPS_LOCATION);
  location.usbDaqBroadcast(true);
  location.sensorBroadcast(true);
  location.label(1);

  // Define record memory
  RcdArena arena;
  SubInserter inserter(arena);

  // Send records
  arena.initialise(RcdHeader::startUp);
  asr.record(arena);
    
  arena.initialise(RcdHeader::runStart);
  asr.record(arena);

  for(unsigned i(0);i<nCfg;i++) {
    arena.initialise(RcdHeader::configurationStart);

    MpsReadoutConfigurationData
      *c(inserter.insert<MpsReadoutConfigurationData>(true));
    c->usbDaqEnableAll(true);

    MpsLocationData<MpsUsbDaqConfigurationData>
      *u(inserter.insert< MpsLocationData<MpsUsbDaqConfigurationData> >(true));
    u->location(location);
    u->data()->spillCycleCount(4096);
    //u->data()->spillCycleCount(20);
    //u->print() << std::endl;

    MpsLocationData<MpsPcb1ConfigurationData>
      *p(inserter.insert< MpsLocationData<MpsPcb1ConfigurationData> >(true));
    p->location(location);
    //p->data()->baseAddress();
    //p->print() << std::endl;

    MpsLocationData<MpsSensor1ConfigurationData>
      *s(inserter.insert< MpsLocationData<MpsSensor1ConfigurationData> >(true));
    s->location(location);
    //s->data()->maskQuadrant(0,false);
    //s->print() << std::endl;

    asr.record(arena);
    
    for(unsigned j(0);j<nBnt;j++) {
      arena.initialise(RcdHeader::bunchTrain);
      asr.record(arena);
      sleep(1);
    }

    arena.initialise(RcdHeader::configurationEnd);
    asr.record(arena);
  }

  arena.initialise(RcdHeader::runEnd);
  asr.record(arena);

  arena.initialise(RcdHeader::shutDown);
  asr.record(arena);

  return 0;
}
