/** @file
 * $Source: /repository/PamOffLineSW/techmodel/CalibS4Reader.cpp,v $
 * $Id: CalibS4Reader.cpp,v 1.5 2008-03-04 18:09:30 messineo Exp $
 * $Author: messineo $
 * 
 * Implementation of the LogReader class.
* ToBeDone:
* Control the CRC for the entire data Packet not just for single records
 */


extern "C" {
#include "CRC.h"
}
#include "ReaderAlgorithms.h"

using namespace pamela::techmodel;


/**
 * Constructor. 
 */
CalibS4Reader::CalibS4Reader(void): 
  TechmodelAlgorithm(PacketType::Log, "TechmodelCalibS4Reader") { 
  calibS4 = new CalibS4Event();
}

/**
 * Get a string with the version info of the algorithm.
 */
std::string CalibS4Reader::GetVersionInfo(void) const {
  return 
    "$Header: /repository/PamOffLineSW/techmodel/CalibS4Reader.cpp,v 1.5 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 CalibS4Reader::Init(PamelaRun *run) {
 
  run->WriteSubPacket(this, &calibS4, calibS4->Class());
}

/**
 * Unpack the CalibS4 event
 */
void CalibS4Reader::PKT_RunEvent(char* subData, long int length) throw (WrongCRCException){
	std::stringstream oss; 
	string msg;	
	 	
	int offset;
    UINT16    subCRC;      //CRC of the data
    UINT16    readCRC;     //CRC read from the end of the subpacket
    int numRecords = ((length - 2)/6);        
    S4::S4Event* rec;
    calibS4->Records->Clear();
    TClonesArray &recs = *(calibS4->Records);

    subCRC = CM_Compute_CRC16(0, (BYTE*)subData, length - 2);
    readCRC = (((UINT16)(subData[length - 2]<<8))&0xFF00) + (((UINT16)subData[length - 1])&0x00FF);
  
    //TODO:check here ....
    //ORIG: if (subCRC != readCRC) throw WrongCRCException(" Wrong CRC for CalibS4 Packet ");
    if (subCRC != readCRC)
    {
    	oss.str("");
    	oss<<"Wrong CRC for CalibS4 Packet: "<<" CRC COMPUTED= "<< subCRC<<" CRC READ=  "<< readCRC;
    	msg=oss.str();
    	PamOffLineSW::mainLogUtil->logError(msg);	
    	throw WrongCRCException(" Wrong CRC for CalibS4 Packet. THE PACKET IS DISCARDED ");
    }	

    for(int i = 0; i < numRecords; i++) {
        offset = i*6; 
        rec = new(recs[i]) S4::S4Event(); //add a new S4Event
        rec->S4_REG_STATUS        = (((UINT8)subData[offset])&0xF0);
        rec->S4_DATA              = ((((UINT16)subData[offset]<<8)&0x0FFF) + (((UINT16)subData[offset+1])&0x00FF));
        rec->S4_CMD_NUM           = (((UINT8)subData[offset+2])&0xFF);
        rec->S4_RESP_LENGHT       = ((((UINT16)subData[offset+3]<<8)&0xFF00) + (((UINT16)subData[offset+4])&0x00FF));
        rec->S4_OVERALL_CHKCODE   = (((UINT8)subData[offset+5])&0xFF);
    }
/*    
    if (subCRC != readCRC)
    {
    	oss.str("");
    	oss<<"Wrong CRC for CalibS4 Packet: "<<" CRC COMPUTED= "<< subCRC<<" CRC READ=  "<< readCRC;
    	msg=oss.str();
    	PamOffLineSW::mainLogUtil->logWarning(msg);	
    	throw WrongCRCException_PKTUsed(" Wrong CRC for CalibS4 Packet. ");
    }
*/
    
}

