/** @file
 * $Source: /home/cvsmanager/yoda/techmodel/CalibCalReader.cpp,v $
 * $Id: CalibCalReader.cpp,v 1.2 2004/07/08 12:31:42 kusanagi Exp $
 * $Author: kusanagi $
 * 
 * Implementation of the LogReader class.
* ToBeDone:
* Control the CRC for the entire data Packet not just for single records
 */

//#define UINT unsigned int
#define BYTE  unsigned char
#include <string>
#include <log4cpp/Category.hh>
#include <fstream>
#include "stdio.h"
/*extern "C" {
    #include "CRC.h"
    // external declaration of the Fortran function
    void calpedestal_(short[], int*, float[96][11][4], float[][11][4], 
                         float[][11][4], float[][11][4], float[][11][4]);
}*/

#include "ReaderAlgorithms.h"
#include "event/CalibCalEvent.h"

using namespace pamela;
using namespace pamela::techmodel;

static log4cpp::Category& cat = log4cpp::Category::getInstance("pamela.techmodel.CalibCalReader");  

/**
 * Constructor. 
 */
CalibCalReader::CalibCalReader(void): 
  TechmodelAlgorithm(PacketType::Log, "TechmodelCalibCalReader") { 
  cat <<  log4cpp::Priority::DEBUG
      <<  "Constructor "
      <<  "\n " << log4cpp::CategoryStream::ENDLINE;
  CalibCal = new CalibCalEvent();
}

/**
 * Get a string with the version info of the algorithm.
 */
std::string CalibCalReader::GetVersionInfo(void) const {
  return 
    "$Header: /home/cvsmanager/yoda/techmodel/CalibCalReader.cpp,v 1.2 2004/07/08 12:31:42 kusanagi Exp $\n";
}

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

/**
 * Unpack the CalibCal event from an input file.
 */
void CalibCalReader::RunEvent(int EventNumber, long int length) {
 
  char     *subData;
  long int  dataLength;
  int ERROR;
  
    //the 2 bytes subtracted belong to the final event CRC bytes
    dataLength = length - (long int)2;

    subData = new char[dataLength];
    InputFile->read(subData, sizeof(unsigned char)*dataLength);

    //Skip the last two crc bytes already checked in UnpackPscu
    //This part have to be refactored!!!! too bad......
    InputFile->seekg((long int)2, std::ios::cur);
               
    //Chiamata alla funzione fortran per la lettura dei piedistalli
    //calpedestal_((short*)subData, &ERROR, CalibCal->cal_ped, CalibCal->cal_good, CalibCal->cal_thr, CalibCal->cal_base, CalibCal->cal_var);
        cat <<  log4cpp::Priority::ERROR
            <<  "Fortran77 function calpedestal error code = " << ERROR
            <<  "\n " << log4cpp::CategoryStream::ENDLINE;
    free(subData);
  }