#ifndef BmlCaen767TestData_HH
#define BmlCaen767TestData_HH

#include <iostream>
#include <fstream>

#include "UtlPack.hh"
#include "BmlCaen767EventDatum.hh"


class BmlCaen767TestData {

public:
  enum {
    versionNumber=0
  };

  enum Pattern {
    count,
    empty,
    event
  };

  BmlCaen767TestData();

  unsigned numberOfRepeats() const;
  void     numberOfRepeats(unsigned n);

  unsigned numberOfWords() const;
  void     numberOfWords(unsigned n);

  void setPattern(Pattern p=count, unsigned n=0);
  
  const BmlCaen767EventDatum* data() const;
        BmlCaen767EventDatum* data();
 
  std::ostream& print(std::ostream &o, std::string s="") const;


private:
  unsigned _numberOfRepeats;
  unsigned _numberOfWords;
};


#ifdef CALICE_DAQ_ICC

#include <cstring>

#include "UtlPrintHex.hh"


BmlCaen767TestData::BmlCaen767TestData() {
  memset(this,0,sizeof(BmlCaen767TestData));
  _numberOfRepeats=1;
}

unsigned BmlCaen767TestData::numberOfRepeats() const {
  return _numberOfRepeats;
}

void BmlCaen767TestData::numberOfRepeats(unsigned n) {
  _numberOfRepeats=n;
}

unsigned BmlCaen767TestData::numberOfWords() const {
  return _numberOfWords;
}

void BmlCaen767TestData::numberOfWords(unsigned n) {
  _numberOfWords=n;
}

void BmlCaen767TestData::setPattern(Pattern p, unsigned n) {
  BmlCaen767EventDatum *a(data());
  //UtlPack *b((UtlPack*)a);

  if(p==count) {
    a[0].setHeader(0x15,0);
    for(unsigned i(1);i<1024-1;i++) a[i].setDatum(0,false,true,i);
    a[1024-1].setEob(0x15,7,1024-1);
    _numberOfWords=1024;
    _numberOfRepeats=32;
  }

  if(p==empty) {
    a[0].setHeader(0x15,0);
    a[1].setEob(0x15,7,0);
    _numberOfWords=2;
    _numberOfRepeats=16*1024;
  }

  if(p==event) {
    a[0].setHeader(0x05,0);

    unsigned channel,time;
    bool lead;
    for(unsigned i(1);i<=n;i++) {
      if((i%2)==1) {
	channel=rand()%8;
	time=(rand()%32)+1000;
	lead=true;
      } else {
	time+=50;
	lead=false;
      }
      a[i].setDatum(channel,false,lead,time);
    }

    a[n+1].setEob(0x05,7,n);

    _numberOfWords=n+2;
    _numberOfRepeats=32*1024/(n+2);
  }
}

const BmlCaen767EventDatum* BmlCaen767TestData::data() const {
  return (const BmlCaen767EventDatum*)(this+1);
}

BmlCaen767EventDatum* BmlCaen767TestData::data() {
  return (BmlCaen767EventDatum*)(this+1);
}

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

  o << s << " Number of repeats = " << _numberOfRepeats << std::endl;

  o << s << " Number of words = " << _numberOfWords << std::endl;
  const BmlCaen767EventDatum *p(data());
  for(unsigned i(0);i<_numberOfWords;i++) {
    if(p[i].label()==BmlCaen767EventDatum::header && i!=0) o << std::endl;
    o << s << " Datum " << std::setw(4) << i;
    p[i].print(o,s+"  ");
  }

  return o;
}

#endif
#endif
