/** @file
 * $Source: /home/cvsmanager/yoda/techmodel/CalibAcReader.cpp,v $
 * $Id: CalibAcReader.cpp,v 2.1 2004/10/17 12:28:38 kusanagi Exp $
 * $Author: kusanagi $
 * 
 * Implementation of the ArrDumpReader 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.CalibAcReader"));

/**
 * Constructor. 
 */
CalibAcReader::CalibAcReader(void): 
  TechmodelAlgorithm(PacketType::CalibAc, "TechmodelCalibAc") { 
  logger->debug(_T("Constructor"));
  CalibAc = new CalibAcEvent();
}

/**
 * Get a string with the version info of the algorithm.
 */
std::string CalibAcReader::GetVersionInfo(void) const {
  return "$Header: /home/cvsmanager/yoda/techmodel/CalibAcReader.cpp,v 2.1 2004/10/17 12:28:38 kusanagi Exp $\n";
}

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

/**
 * Unpack the CalibAc event from an input file.
 */
void CalibAcReader::RunEvent(int EventNumber, long int dataLength) throw (Exception){
  char   subData[dataLength];
  InputFile->read(subData, sizeof(unsigned char)*dataLength);
  
    struct calibstruct output[2];
    int ERROR;
    CalibAc->ERROR = ACcalib(dataLength, (unsigned char*)subData, &(*output));

    for (int i = 0; i<2; i++){
        CalibAc->header[i] = output[i].header;
        memcpy(CalibAc->status[i],     output[i].status,     sizeof(output[i].status));
        memcpy(CalibAc->temp[i],       output[i].temp,       sizeof(output[i].temp));
        memcpy(CalibAc->DAC1[i],       output[i].DAC1,       sizeof(output[i].DAC1));
        memcpy(CalibAc->DAC2[i],       output[i].DAC2,       sizeof(output[i].DAC2));
        memcpy(CalibAc->regist[i],     output[i].regist,     sizeof(output[i].regist));
        memcpy(CalibAc->time[i],       output[i].time,       sizeof(output[i].time));
        CalibAc->n_tr[i] = output[i].n_tr;
        memcpy(CalibAc->hitmap_tr[i],  output[i].hitmap_tr,  sizeof(output[i].hitmap_tr));
        memcpy(CalibAc->curve1[i],     output[i].curve1,     sizeof(output[i].curve1));
        memcpy(CalibAc->curve2[i],     output[i].curve2,     sizeof(output[i].curve2));
        CalibAc->iCRC[i] = output[i].iCRC;
        CalibAc->tail[i] = output[i].tail;
        CalibAc->CRC[i]  = output[i].CRC;
    }

    delete [] subData;
  }
