/** @file
 * $Author: kusanagi $
 * $Date: 2006/05/30 19:10:03 $
 * $Revision: 6.2 $
 * 
 * Implementation of the InitHeaderReader class.
 */

#include "ReaderAlgorithms.h"

using namespace pamela::techmodel;

static log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger(_T("pamela.techmodel.InitHeaderReader"));

/**
 * Constructor. 
 */
InitHeaderReader::InitHeaderReader(void): 
  TechmodelAlgorithm(PacketType::InitHeader, "TechmodelInitHeaderReader") { 
  logger->debug(_T("Constructor"));
  initHeader = new InitHeaderEvent();
}

/**
 * Get a string with the version info of the algorithm.
 */
std::string InitHeaderReader::GetVersionInfo(void) const {
  return 
    "$Header: /afs/ba.infn.it/user/pamela/src/CVS/yoda/techmodel/InitHeaderReader.cpp,v 6.2 2006/05/30 19:10:03 kusanagi Exp $\n";
}

/**
 Initialize the algorithm with a special run. This will initialize the
 * event reader routines for all packet types.
 *
 * @param run 
 */
void InitHeaderReader::Init(PamelaRun *run) {
  logger->debug(_T("Initialize"));
  SetInputStream(run);
  run->WriteSubPacket(this, &initHeader, initHeader->Class());
}


/**
 * Unpack the InitHeader event from an input file.
 * @param EventNumber 
 * @param dataLength 
 */
void InitHeaderReader::RunEvent(int EventNumber, long int dataLength) throw (WrongCRCException){

    char      subData[dataLength];
    UINT16    subCRC;      //calculated CRC of the data
    UINT16    readCRC;     //CRC read from the end of the subpacket
    long int  length = dataLength - 2; //the block of data
    memset(subData,  0, dataLength*sizeof(char));
    InputFile->read(subData, sizeof(subData));
    subCRC  = CM_Compute_CRC16(0, (UINT8*)subData, length);
    readCRC = (((UINT16)(subData[dataLength - 2]<<8))&0xFF00) + (((UINT16)subData[dataLength - 1])&0x00FF);

    if (subCRC != readCRC) throw WrongCRCException(" Wrong CRC for InitHeader Packet ");
	initHeader->initHeaderData        = new TArrayC(length, subData);
}

