/** @file
 * $Source: /home/cvsmanager/yoda/techmodel/Calib2_Ac2Reader.cpp,v $
 * $Id: Calib2_Ac2Reader.cpp,v 2.5 2005/01/29 00:26:55 kusanagi Exp $
 * $Author: kusanagi $
 * 
 * Implementation of the Calib2_Ac2Reader class.
 */

#include <string>
#include <log4cxx/logger.h>
#include <fstream>
#include "stdio.h"
extern "C" {
    #include "CRC.h"
    #include "forroutines/anticounter/AC.h"
    extern int ACcalib(int length, unsigned char* calibpointer, struct calibstruct* calibpointer);
}

#include "ReaderAlgorithms.h"

using namespace pamela;
using namespace pamela::techmodel;

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

/**
 * Constructor. 
 */
Calib2_Ac2Reader::Calib2_Ac2Reader(void): 
  TechmodelAlgorithm(PacketType::Calib2_Ac2, "Calib2_Ac2") { 
  logger->debug(_T("Constructor"));
  calib2_Ac2 = new Calib2_Ac2Event();
}

/**
 * Get a string with the version info of the algorithm.
 */
std::string Calib2_Ac2Reader::GetVersionInfo(void) const {
  return "$Header: /home/cvsmanager/yoda/techmodel/Calib2_Ac2Reader.cpp,v 2.5 2005/01/29 00:26:55 kusanagi Exp $\n";
}

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

/**
 * Unpack the CalibAc event from an input file.
 */
void Calib2_Ac2Reader::RunEvent(int EventNumber, long int dataLength) throw (Exception){
  
    char   *subData = new char[dataLength];
    struct calibstruct *output = {0};

    InputFile->read(subData, sizeof(unsigned char)*dataLength);

    for (int i = 0; i < dataLength; i++){
        printf("input2 %i   %x \n", i, subData[i]);
    }
    
    calib2_Ac2->ERROR = ACcalib(dataLength, (unsigned char*)subData, output);
    memcpy(calib2_Ac2->header,     output->header,     sizeof(output->header));
    memcpy(calib2_Ac2->status,     output->status,     sizeof(output->status));
    memcpy(calib2_Ac2->temp,       output->temp,       sizeof(output->temp));
    memcpy(calib2_Ac2->DAC1,       output->DAC1,       sizeof(output->DAC1));
    memcpy(calib2_Ac2->DAC2,       output->DAC2,       sizeof(output->DAC2));
    memcpy(calib2_Ac2->regist,     output->regist,     sizeof(output->regist));
    memcpy(calib2_Ac2->time,       output->time,       sizeof(output->time));
    calib2_Ac2->n_tr = output->n_tr;
    memcpy(calib2_Ac2->hitmap_tr,  output->hitmap_tr,  sizeof(output->hitmap_tr));
    memcpy(calib2_Ac2->curve1,     output->curve1,     sizeof(output->curve1));
    memcpy(calib2_Ac2->curve2,     output->curve2,     sizeof(output->curve2));
    calib2_Ac2->iCRC        = output->iCRC;
    calib2_Ac2->tail        = output->tail;
    calib2_Ac2->CRC         = output->CRC;
    calib2_Ac2->CRCcheck    = output->CRCcheck;
    
  
    //delete [] subData;
  }