/** @file
 * $Source: /home/cvsmanager/yoda/techmodel/TsbTReader.cpp,v $
 * $Id: TsbTReader.cpp,v 6.1 2006/05/30 19:10:02 kusanagi Exp $
 * $Author: kusanagi $
 * 
 * Implementation of the TsbTReader class.
 */

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

using namespace pamela::techmodel;

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

/**
 * Constructor. 
 */
TsbTReader::TsbTReader(void): 
  TechmodelAlgorithm(PacketType::TsbT, "TechmodelTsbT") { 
  TsbT = new TsbTEvent();
}

/**
 * Get a string with the version info of the algorithm.
 */
std::string TsbTReader::GetVersionInfo(void) const {
  return     "$Header: /home/cvsmanager/yoda/techmodel/TsbTReader.cpp,v 6.1 2006/05/30 19:10:02 kusanagi Exp $\n";
}

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

/**
 * Unpack the TsbT event from an input file.
 */
void TsbTReader::RunEvent(int EventNumber, long int length) throw (WrongCRCException){
 
    char      subData[length];
    UINT16    subCRC;      //calculated CRC of the data
    UINT16    readCRC;     //CRC read from the end of the subpacket
    long int  dataLength = length - 2; //the block of data
      
    InputFile->read(subData, sizeof(subData));
    subCRC  = CM_Compute_CRC16(0, (UINT8*)subData, dataLength);
    readCRC = (((UINT16)(subData[length - 2]<<8))&0xFF00) + (((UINT16)subData[length - 1])&0x00FF);
    
    if (subCRC != readCRC) throw WrongCRCException(" Wrong CRC for TsbT Packet ");
    /*if (subCRC != readCRC) {
        throw WrongCRCException("WRONG CRC FOR TsbT PACKET."); 
    }*/
    
    TsbTRecord* rec;
    TsbT->Records->Clear();
    TClonesArray &recs = *(TsbT->Records);
    
    int i = 0;
    long int offset = 0; //dataLength/31;
    while (offset < dataLength){
        rec               = new(recs[i++]) TsbTRecord(); //add a new TsbT
        rec->RECORD_OBT  = (((UINT32)subData[offset]<<24)&0xFF000000) + (((UINT32)subData[offset+1]<<16)&0x00FF0000) +  (((UINT32)subData[offset+2]<<8)&0x0000FF00) + (((UINT32)subData[offset+3])&0x000000FF);
        rec->STATUS_CODE = subData[offset+4];
        for (int j=0; j < 13; j++){
           rec->TEMPERATURES[j]  = ((((UINT16)subData[offset+5+(2*j)]<<8)&0xFF00) + (((UINT16)subData[offset+6+(2*j)])&0x00FF));
        }
        offset = offset + 31;
    }
}

