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

#include "ReaderAlgorithms.h"

using namespace pamela::techmodel;

/**
 * Constructor. 
 */
CalibHeaderReader::CalibHeaderReader(void): 
  TechmodelAlgorithm(PacketType::CalibHeader, "TechmodelCalibHeaderReader") { 
  calibHeader = new CalibHeaderEvent();
}

/**
 * Get a string with the version info of the algorithm.
 */
std::string CalibHeaderReader::GetVersionInfo(void) const {
  return 
    "$Header: /repository/PamOffLineSW/techmodel/CalibHeaderReader.cpp,v 1.4 2008-03-04 18:09:30 messineo Exp $\n";
}

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

/**
 * Unpack the CalibHeader event from an input file.
 */
void CalibHeaderReader::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 CalibHeader Packet ");
    if (subCRC != readCRC)
    {
    	oss.str("");
    	oss<<"Wrong CRC for CalibHeader Packet: "<<" CRC COMPUTED= "<< subCRC<<" CRC READ=  "<< readCRC;
    	msg=oss.str();
    	PamOffLineSW::mainLogUtil->logError(msg);	
    	throw WrongCRCException(" Wrong CRC for CalibHeader Packet. THE PACKET IS DISCARDED ");
    }
    	
    calibHeader->calibHeaderData        = new TArrayC(length, subData);
/*      
    if (subCRC != readCRC)
    {
    	oss.str("");
    	oss<<"Wrong CRC for CalibHeader Packet: "<<" CRC COMPUTED= "<< subCRC<<" CRC READ=  "<< readCRC;
    	msg=oss.str();
    	PamOffLineSW::mainLogUtil->logWarning(msg);	
    	throw WrongCRCException_PKTUsed(" Wrong CRC for CalibHeader Packet. ");
    }
*/    	 
}


