#ifndef DaqSoftware_HH
#define DaqSoftware_HH

#ifndef CALICE_DAQ_TIME
#define CALICE_DAQ_TIME 0
#endif

#include <string>
#include <fstream>
#include <iostream>

#include "DaqMessage.hh"


class DaqSoftware : public DaqMessage {

public:
  enum {
    versionNumber=0
  };

  DaqSoftware();

  unsigned compilationTime() const;
  void     compilationTime(unsigned n);
  void setCompilationTime();

  std::string version(unsigned i) const;
  void        version(unsigned i, const std::string &v);
  void setVersions();

  std::ostream& print(std::ostream &o, std::string s="") const;


protected:
  unsigned _compilationTime;
  char _recordsVersion[16];
  char _daquserVersion[16];
  char _onlineVersion[16];
};


#ifdef CALICE_DAQ_ICC

#include <time.h>

#include <cstring>

DaqSoftware::DaqSoftware() : DaqMessage("Undefined") {
  _compilationTime=CALICE_DAQ_TIME;

  strncpy(_recordsVersion,"VXX-XX",15);
  _recordsVersion[15]='\0';

  strncpy(_daquserVersion,"VXX-XX",15);
  _daquserVersion[15]='\0';

  strncpy(_onlineVersion,"VXX-XX",15);
  _onlineVersion[15]='\0';
}

unsigned DaqSoftware::compilationTime() const {
  return _compilationTime;
}

void DaqSoftware::compilationTime(unsigned n) {
  _compilationTime=n;
}

void DaqSoftware::setCompilationTime() {
  _compilationTime=CALICE_DAQ_TIME;
}

std::string DaqSoftware::version(unsigned i) const {
  assert(i<3);
  if(i==0) return _recordsVersion;
  if(i==1) return _daquserVersion;
  return _onlineVersion;
}

void DaqSoftware::version(unsigned i, const std::string &v) {
  assert(i<3);

  char *p(_onlineVersion);
  if(i==0) p=_recordsVersion;
  if(i==1) p=_daquserVersion;

  for(unsigned i(0);i<v.size() && i<15;i++) p[i]=v[i];
  if(v.size()<16) p[v.size()]='\0';
  p[15]='\0';
}

void DaqSoftware::setVersions() {

  // Attempt to read version information
  char *p(0);
  for(unsigned i(0);i<3;i++) {
    std::ifstream fin;

    if(i==0) {
      fin.open("records/History");
      p=_recordsVersion;
    }
    if(i==1) {
      fin.open("daquser/History");
      p=_daquserVersion;
    }
    if(i==2) {
      fin.open("online/History");
      p=_onlineVersion;
    }
  
    for(unsigned j(0);j<15 && fin;j++) fin >> p[j];
    p[15]='\0';

    fin.close();
  }
}

std::ostream& DaqSoftware::print(std::ostream &o, std::string s) const {
  o << s << "DaqSoftware::print()" << std::endl;
  DaqMessage::print(o,s+" ");

  o << s << " Compilation time " << _compilationTime << " = "
    << ctime((const time_t*)&_compilationTime);

  o << s << " Records package version = " << _recordsVersion << std::endl;
  o << s << " Daquser package version = " << _daquserVersion << std::endl;
  o << s << " Online  package version = " << _onlineVersion << std::endl;

  return o;
}

#endif
#endif
