#include "runnerDefine.icc"

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

#include <iostream>

#include "UtlArguments.hh"
#include "RcdArena.hh"
#include "RcdIoSkt.hh"
#include "HstGeneric.hh"
#include "RunWriterSlow.hh"
#include "RunWriterDataMultiFile.hh"
#include "HstGeneric.hh"
#include "RunLock.hh"

using namespace std;

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

  unsigned eTime(CALICE_DAQ_TIME);
  cout << argv[0] << " compiled at " << ctime((const time_t*)&eTime);

  // Check if not compiled for socket use  
#ifndef HST_SKT
  std::cout << argv[0] << " not compiled for use; exiting" << std::endl;

#else

  // Handle arguments
  UtlArguments argh(argc,argv);
  
  const unsigned port(argh.optionArgument('n',1127,"Port"));
  const unsigned printLevel(argh.optionArgument('p',9,"Print level"));
  //const unsigned histBits(argh.optionArgument('b',hstBits.word(),
  //			   "Histogram selection bits"));

  if(argh.help()) return 0;
  
  std::cout << "Port set to " << port << std::endl;
  std::cout << "Print level set to " << printLevel << std::endl;
  //std::cout << "Histogram selection bits set to "
  //	    << printHex(histBits) << std::endl;
  
  // Make a sktHstGeneric.lock file to prevent starting this twice
  RunLock lock(argv[0]);

#include "readOnly.icc"

  // Set up the socket
  RcdIoSkt s;
  if(!s.open(port)) {
    std::cerr << "Failed to open socket port" << std::endl;
    assert(false);
  }

  // Set up the histogramming
  //HstGeneric c(histBits);
  vrub.printLevel(printLevel);

  // Set up the memory for the records
  RcdArena r;
  r.initialise(RcdHeader::startUp);
  
  // Loop until shutDown seen
  while(r.recordType()!=RcdHeader::shutDown) {
    
    // Read next record from socket
    assert(s.read(r));

    // Check for runStart record
    if(r.recordType()==RcdHeader::runStart) {

      // Access the DaqRunStart to get print level
      SubAccessor accessor(r);
      std::vector<const DaqRunStart*> v(accessor.extract<DaqRunStart>());
      if(v.size()>0) {
        vrub.printLevel(v[0]->runType().printLevel());
      }
    }

    // Reset printLevel back to original value during shutDown
    if(r.recordType()==RcdHeader::shutDown) vrub.printLevel(printLevel);

    // Process record through histogramming
    assert(vrub.record(r));
  }

  // Close socket and exit
  assert(s.close());

#endif

  return 0;
}
