#include "PamVMCDigRunTrailer.h"

ClassImp(PamVMCDigRunTrailer)
#include "CRC.h"
void PamVMCDigRunTrailer:: DigitizeRunTrailer(){
  
  UChar_t buffRT[18];

  // header: 16 bytes
  DigitizePSCU(18,0x21);

   // pkt_counter (uint32)
  fraw->AddCounterPhys();
  fraw->AddCounter();
  UInt_t countphys = fraw->GetCounterPhys();
  while ( countphys > 16777215 )
    countphys -= 16777215;
  //
  fraw->SetCounterPhys(countphys);
  buffRT[0] = ((UChar_t)(countphys >> 24));
  buffRT[1] = ((UChar_t)(countphys >> 16));
  buffRT[2] = ((UChar_t)(countphys >> 8));
  buffRT[3] = (UChar_t)countphys;

  // pkt_readyCounter: valid packets in the run (uint32)
  buffRT[4] = 0x00;
  buffRT[5] = 0x00;
  buffRT[6] = 0x00;
  buffRT[7] = 0x00;

  // obt (uint32)
  ULong64_t obt = fraw->GetOBT() + 30LL;
  while ( obt > 4294967295LL )
    obt -= 4294967295LL;
  UInt_t Uobt = UInt_t(obt);
  fraw->SetOBT(Uobt);
  //
  buffRT[8]  = ((UChar_t)(Uobt >> 24));
  buffRT[9]  = ((UChar_t)(Uobt >> 16));
  buffRT[10] = ((UChar_t)(Uobt >> 8));
  buffRT[11] = (UChar_t)Uobt;

  // last time_sync_info (uint32)
  buffRT[12] = 0x00;
  buffRT[13] = 0x00;
  buffRT[14] = 0x00;
  buffRT[15] = 0x00;

  // crc (uint16)

  UShort_t crcRT = (UShort_t)CM_Compute_CRC16((UINT16)0, (BYTE*)&buffRT, (UINT32)(16));
  buffRT[16] = ((UChar_t)(crcRT >> 8));
  buffRT[17] = (UChar_t)crcRT;

  for(Int_t i=0; i<18; i++) fDataPSCU.push_back(buffRT[i]);

  cout<<"Size of RunTrailer = "<<fDataPSCU.size()<<endl;
}


void PamVMCDigRunTrailer::WriteRunTrailer(){
  
  fraw->WritePSCU(&fDataPSCU);
}

