
// Implementation of the CalibCalPulse1Reader class.
 

extern "C" {
#include "CRC.h"  
    //Struct per il passaggio di dati da e verso la chiamata fortran
extern struct {
        int   iev;
        int   pstwerr[4];
        float pperror[4];
        float calpuls[4][11][96];
    } calpul_; 
    
    //external declaration of the Fortran function 
    void calpulse_(char*, long int*, int*);
}

#include "ReaderAlgorithms.h"

using namespace pamela::techmodel;


/**
 * Constructor. 
 */
CalibCalPulse1Reader::CalibCalPulse1Reader(void): 
  TechmodelAlgorithm(PacketType::CalibCalPulse1, "TechmodelCalibCalPulse1Reader") { 
  calibCalPulse1 = new CalibCalPulse1Event();
}

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

/**
 * Unpack the CalibCalPulse1 event
 */
void CalibCalPulse1Reader::PKT_RunEvent(char* packetData, long int dataLength) throw (Exception){
	
	string msg;    
	std::stringstream oss;       
    int         ERROR;
    calpulse_(packetData, &dataLength, &ERROR);
    
    calibCalPulse1->unpackError = ERROR;
    oss.str("");    
    if (ERROR != 0) {
        char *errmsg;
        switch (ERROR){
            case 1: errmsg = "CALORIMETER NOT FOUND";
        }
        oss << "CalibCalPulse1: Fortran77 function calpulse error code = " << ERROR
            <<  " " << errmsg;
        msg=oss.str();
        PamOffLineSW::mainLogUtil->logWarning(msg);	
      } //else {
      //Store the unpacked data
        calibCalPulse1->iev = calpul_.iev;
        memcpy(calibCalPulse1->pstwerr, calpul_.pstwerr, sizeof(calibCalPulse1->pstwerr));
        memcpy(calibCalPulse1->pperror, calpul_.pperror, sizeof(calibCalPulse1->pperror));
    //--------have to invert array because of FORTRAN <-> C different management of the indexes
        float tempCalpuls[96][11][4];
        memcpy(tempCalpuls, calpul_.calpuls, sizeof(tempCalpuls));
        for (int i = 0; i < 4; i++){
            for (int j = 0; j <11; j++){
                for (int z = 0; z < 96; z++){
                    calibCalPulse1->calpuls[i][j][z]  = tempCalpuls[z][j][i];
                }
            }
        }
   //-----------------------------------------------------------------------------------------
    //}
}
