#include "Digitizer.h"


void Digitizer::DigitizePSCU(UInt_t length, UChar_t type, UShort_t *pPSCU) {
  //
  UChar_t buff[16];
  //
  // CPU signature
  //  
  buff[0] = 0xFA;
  buff[1] = 0xFE;
  buff[2] = 0xDE;
  //
  // packet type (twice)
  //
  buff[3] = type;
  buff[4] = type;
  //
  // counter
  //
  fCounter++;
  while ( fCounter > 16777215 ){
    fCounter -= 16777215;
  };
  //
  buff[5] = (UChar_t)(fCounter >> 16);
  buff[6] = (UChar_t)(fCounter >> 8);
  buff[7] = (UChar_t)fCounter;
  //
  // on board time
  //
  ULong64_t obt = fOBT + 30LL;
  //
  while ( obt > 4294967295LL ){
    obt -= 4294967295LL;
  };
  fOBT = (UInt_t)obt;
  //
  buff[8] = (UChar_t)(fOBT >> 24);
  buff[9] = (UChar_t)(fOBT >> 16);
  buff[10] = (UChar_t)(fOBT >> 8);
  buff[11] = (UChar_t)fOBT;
  //
  // Packet length
  //
  fLen = length;
  //
  buff[12] = (UChar_t)(fLen >> 16);
  buff[13] = (UChar_t)(fLen >> 8);
  buff[14] = (UChar_t)fLen;
  //
  // CPU header CRC
  //
  buff[15] = (BYTE)CM_Compute_CRC16((UINT16)0, (BYTE*)&buff, (UINT32)15);
  //
  //memcpy(fDataPSCU,buff,16*sizeof(UChar_t));
  memcpy(pPSCU,buff,16*sizeof(UChar_t));
  //
};
void Digitizer::AddPadding(){
  //
  Float_t pd0 = (fLen+16)/64.;
  Float_t pd1 = pd0 - (Float_t)int(pd0);
  Float_t padfrac = 64. - pd1 * 64.;
  //
  UInt_t padbytes = (UInt_t)padfrac;
  if ( padbytes > 0 && padbytes < 64 ){
    //
    // here the padding length
    //
    fPadding = padbytes+64;
    //
    // random padding bytes
    //
    for (Int_t ur=0; ur<32; ur++){
      fDataPadding[ur] = (UShort_t)rand();
    };
  };
};
