//
// $Id: DhcFeHitData.hh,v 1.1 2008/06/27 10:34:05 meyern Exp $
//

#ifndef DhcFeHitData_HH
#define DhcFeHitData_HH

#include <string>
#include <iostream>

#include "UtlPack.hh"


class DhcFeHitData {

public:
  enum {
    versionNumber=0
  };

  DhcFeHitData();

  unsigned dcad() const;
  unsigned scad() const;
  unsigned dcalad() const;
  unsigned febad() const;
  unsigned dcolad() const;
  unsigned timestamp() const;
  unsigned hitsHi() const;
  unsigned hitsLo() const;
  unsigned trg() const;
  unsigned err() const;
  unsigned char chksum() const;

  bool verify() const;

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


private:
  UtlPack _data[4];
};

DhcFeHitData::DhcFeHitData() {
}

unsigned DhcFeHitData::dcad() const {
  return _data[0].bits(24,26);
}

unsigned DhcFeHitData::scad() const {
  return _data[0].bits(27,30);
}

unsigned DhcFeHitData::dcalad() const {
  return _data[0].bits(16,17);
}

unsigned DhcFeHitData::febad() const {
  return _data[0].bits(18,19);
}

unsigned DhcFeHitData::dcolad() const {
  return _data[0].bits(20,23);
}

unsigned DhcFeHitData::timestamp() const {
  return  _data[0].bits(0,15)<<8 | _data[1].byte(3);
}

unsigned DhcFeHitData::hitsHi() const {
  return _data[1].bits(0,23)<<8 | _data[2].byte(3);
}

unsigned DhcFeHitData::hitsLo() const {
  return _data[2].bits(0,23)<<8 | _data[3].byte(3);
}

unsigned DhcFeHitData::trg() const {
  return _data[3].bit(15);
}

unsigned DhcFeHitData::err() const {
  return _data[3].bits(8,10);
}

unsigned char DhcFeHitData::chksum() const {
  return _data[3].byte(0);
}

bool DhcFeHitData::verify() const {
  // compute chksum
  unsigned char sum =
    static_cast<unsigned char>(_data[0].byte(3)&0x87) +
    static_cast<unsigned char>(_data[0].byte(2)&0x0f);

  for (int i(2); i<15; i++)
    sum += static_cast<unsigned char>(_data[i/4].byte(3-(i%4)));

  return (sum == chksum());
}

std::ostream& DhcFeHitData::print(std::ostream &o, std::string s) const {

  o << s << std::hex;
  o << s << "dcad:" << dcad();
  o << s << "scad:" << scad();
  o << s << "dcalad:" << dcalad();
  o << s << "febad:" << febad();
  o << s << "dcolad:" << dcolad();
  o << s << "trg:" << trg();
  o << s << "err:" << err();
  o << s << "hits:";
  o << s << std::setfill('0') << std::setw(8) << hitsHi();
  o << s << std::setfill('0') << std::setw(8) << hitsLo();
  o << s << "ts:" << std::dec << timestamp();
  o << s << std::setfill(' ');
  o << s << std::endl;

  return o;
}

#endif // DhcFeHitData_HH
