#ifndef BmlCaen767TdcErrorData_HH
#define BmlCaen767TdcErrorData_HH

#include <iostream>
#include <fstream>

#include "UtlPack.hh"


class BmlCaen767TdcErrorData {

public:
  enum {
    versionNumber=0
  };

  BmlCaen767TdcErrorData();

  bool notLocked(unsigned t) const;
  bool hitError(unsigned t) const;
  bool eventBufferOverflow(unsigned t) const;
  bool triggerBufferOverflow(unsigned t) const;

  void tdcErrors(unsigned t, unsigned short r);
 
  std::ostream& print(std::ostream &o, std::string s="") const;


private:
  UtlPack _errors[2];
};


#ifdef CALICE_DAQ_ICC

#include <cstring>

#include "UtlPrintHex.hh"


BmlCaen767TdcErrorData::BmlCaen767TdcErrorData() {
  memset(this,0,sizeof(BmlCaen767TdcErrorData));
}

bool BmlCaen767TdcErrorData::notLocked(unsigned t) const {
  return _errors[t/2].bit(0+16*(t%2));
}

bool BmlCaen767TdcErrorData::hitError(unsigned t) const {
  return _errors[t/2].bit(1+16*(t%2));
}

bool BmlCaen767TdcErrorData::eventBufferOverflow(unsigned t) const {
  return _errors[t/2].bit(2+16*(t%2));
}

bool BmlCaen767TdcErrorData::triggerBufferOverflow(unsigned t) const {
  return _errors[t/2].bit(3+16*(t%2));
}

void BmlCaen767TdcErrorData::tdcErrors(unsigned t, unsigned short r) {
  assert(t<4);
  _errors[t/2].halfWord(t%2,r);
}

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

  for(unsigned i(0);i<4;i++) {
    o << s << " TDC" << i << " Error word = " << printHex(_errors[i/2].halfWord(i%2)) << std::endl;
    if(notLocked(i))             o << s << "  Not locked" << std::endl;
    if(hitError(i))              o << s << "  Hit error" << std::endl;
    if(eventBufferOverflow(i))   o << s << "  Event buffer overflow" << std::endl;
    if(triggerBufferOverflow(i)) o << s << "  Trigger buffer overflow" << std::endl;
  }

  return o;
}

#endif
#endif
