/** @file
 * $Author: messineo $
 * $Date: 2008-03-04 18:09:31 $
 * $Revision: 1.4 $
 * 
 * Implementation of the CalibTrailerReader class.
 */ 

#include "ReaderAlgorithms.h"

using namespace pamela::techmodel;


/**
 * Constructor. 
 */
CalibTrailerReader::CalibTrailerReader(void): 
  TechmodelAlgorithm(PacketType::CalibTrailer, "TechmodelCalibTrailerReader") { 
  calibTrailer = new CalibTrailerEvent();
}

/**
 * Get a string with the version info of the algorithm.
 */
std::string CalibTrailerReader::GetVersionInfo(void) const {
  return 
    "$Trailer: /home/cvsmanager/yoda/techmodel/CalibTrailerReader.cpp,v 1.1.1.1 2004/07/06 12:20:23 Maurizio Nagni Exp $\n";
}

/**
 * Initialize the algorithm with a special run. This will initialize the
 * event reader routines for all packet types.
 */
void CalibTrailerReader::Init(PamelaRun *run) {
  run->WriteSubPacket(this, &calibTrailer, calibTrailer->Class());
}

/**
 * Unpack the CalibTrailer event from an input file.
 */
void CalibTrailerReader::PKT_RunEvent(char* subData, long int dataLength) throw (WrongCRCException){
	std::stringstream oss; 
	string msg;	
	
    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
   
    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 CalibTrailer Packet ");
    if (subCRC != readCRC)
    {
    	oss.str("");
    	oss<<"Wrong CRC for CalibTrailer Packet: "<<" CRC COMPUTED= "<< subCRC<<" CRC READ=  "<< readCRC;
    	msg=oss.str();
    	PamOffLineSW::mainLogUtil->logError(msg);	
    	throw WrongCRCException(" Wrong CRC for CalibTrailer Packet. THE PACKET IS DISCARDED ");
    }

    calibTrailer->calibTrailerData        = new TArrayC(length, subData);
/*
    if (subCRC != readCRC)
    {
    	oss.str("");
    	oss<<"Wrong CRC for CalibTrailer Packet: "<<" CRC COMPUTED= "<< subCRC<<" CRC READ=  "<< readCRC;
    	msg=oss.str();
    	PamOffLineSW::mainLogUtil->logWarning(msg);	
    	throw WrongCRCException_PKTUsed(" Wrong CRC for CalibTrailer Packet. ");
    }
 */ 	 
}

