/** @file
 * $Source: /home/cvsmanager/yoda/techmodel/CalibTrk2Reader.cpp,v $
 * $Id: CalibTrk2Reader.cpp,v 4.4 2005/05/28 10:44:11 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 <log4cxx/logger.h>
extern "C" {
    #include "CRC.h"
    //Passo il path verso la il file temporaneo
    extern void trkcalibpkt_(int*, char*); 

    //Struct per il passaggio di dati da e verso la chiamata fortran
  extern struct {
      int   DAQmode[6];
      int   DSPnumber[6];
      int   calibnumber[6];
      int   ncalib_event[6];
      int   ped_l1[6];
      int   ped_l2[6];
      int   ped_l3[6];
      int   sig_l1[6];
      int   sig_l2[6];
      int   sig_l3[6];
      int   nbad_l1[6];
      int   nbad_l2[6];
      int   nbad_l3[6];
      int   cal_flag[6];
      float DSPped_par[6][3072];
      float DSPsig_par[6][3072];
      int   DSPbad_par[6][3072];
    } trkcalib_; 
#include <dirent.h>
}

#include <fstream>
#include "stdio.h"
#include "ReaderAlgorithms.h"

#include "event/CalibTrk2Event.h"

using namespace pamela;
using namespace pamela::techmodel;

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

/**
 * Constructor. 
 */
CalibTrk2Reader::CalibTrk2Reader(void): 
  TechmodelAlgorithm(PacketType::CalibTrk2, "TechmodelCalibTrk2Reader") { 
  logger->debug(_T("Constructor"));
  calibTrk2 = new CalibTrk2Event();
}

/**
 * Get a string with the version info of the algorithm.
 */
std::string CalibTrk2Reader::GetVersionInfo(void) const {
  return 
    "$Header: /home/cvsmanager/yoda/techmodel/CalibTrk2Reader.cpp,v 4.4 2005/05/28 10:44:11 kusanagi Exp $\n";
}

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

/**
 * Unpack the CalibTrk2 event from an input file.
 */
void CalibTrk2Reader::RunEvent(int EventNumber, long int dataLength) throw (Exception){
    std::stringstream oss;    
    char      subData[dataLength];
    int       ERROR;    
 
    InputFile->read(subData, sizeof(unsigned char)*dataLength);
    
    //Scrivo un file temporaneo per passarlo alla routine
    //Speriamo di cambiare la routine per passargli un buffer.....
    oss.str("");
    oss << getenv("YODA_DATA") << "/" << time(NULL) << "trc2.dat";
    FILE *pfile;
    pfile = fopen(oss.str().c_str(), "wb");
    fwrite(subData, 1, dataLength, pfile);
    fclose(pfile);

    //Call to the FORTRAN routin that unpack tracker events
    trkcalibpkt_(&ERROR, (char*)oss.str().c_str());

    calibTrk2->unpackError = ERROR;
    remove(oss.str().c_str());
    if (ERROR != 0) {
        oss.str("");
        oss <<  "Fortran77 function trkcalibpkt error code = " << ERROR;
        logger->warn(oss.str().c_str());
    }
    //delete the temporary file
    remove((char*)oss.str().c_str());

    //Store the unpacked data
    memcpy(calibTrk2->DAQmode,      trkcalib_.DAQmode,     sizeof(calibTrk2->DAQmode));
    memcpy(calibTrk2->DSPnumber,    trkcalib_.DSPnumber,   sizeof(calibTrk2->DSPnumber));
    memcpy(calibTrk2->calibnumber,  trkcalib_.calibnumber, sizeof(calibTrk2->calibnumber));
    memcpy(calibTrk2->DSPnumber,    trkcalib_.ncalib_event,  sizeof(calibTrk2->ncalib_event));
    memcpy(calibTrk2->ped_l1,       trkcalib_.ped_l1,     sizeof(calibTrk2->ped_l1));
    memcpy(calibTrk2->ped_l2,       trkcalib_.ped_l2,     sizeof(calibTrk2->ped_l2));
    memcpy(calibTrk2->ped_l3,       trkcalib_.ped_l3,     sizeof(calibTrk2->ped_l3));
    memcpy(calibTrk2->sig_l1,       trkcalib_.sig_l1,     sizeof(calibTrk2->sig_l1));
    memcpy(calibTrk2->sig_l2,       trkcalib_.sig_l2,     sizeof(calibTrk2->sig_l2));
    memcpy(calibTrk2->sig_l3,       trkcalib_.sig_l3,     sizeof(calibTrk2->sig_l3));
    memcpy(calibTrk2->nbad_l1,      trkcalib_.nbad_l1,    sizeof(calibTrk2->nbad_l1));
    memcpy(calibTrk2->nbad_l2,      trkcalib_.nbad_l2,    sizeof(calibTrk2->nbad_l2));
    memcpy(calibTrk2->nbad_l3,      trkcalib_.nbad_l3,    sizeof(calibTrk2->nbad_l3));
    memcpy(calibTrk2->cal_flag,     trkcalib_.cal_flag,   sizeof(calibTrk2->cal_flag));      
//        memcpy(calibTrk2->DSPbad_par,   trkcalib_.DSPbad_par, sizeof(calibTrk2->DSPbad_par));      
//        memcpy(calibTrk2->DSPped_par,   trkcalib_.DSPped_par, sizeof(calibTrk2->DSPped_par));      
//        memcpy(calibTrk2->DSPsig_par,   trkcalib_.DSPsig_par, sizeof(calibTrk2->DSPsig_par));      
//--------have to invert array because of FORTRAN <-> C different management of the indexes
    int     tempBad_par[3072][6];
    float   tempPed_par[3072][6];
    float   tempSig_par[3072][6];
    memcpy(tempBad_par,trkcalib_.DSPbad_par, sizeof(tempBad_par));      
    memcpy(tempPed_par,trkcalib_.DSPped_par, sizeof(tempPed_par));      
    memcpy(tempSig_par,trkcalib_.DSPsig_par, sizeof(tempSig_par));

    for (int i = 0; i < 6; i++){
        for (int j = 0; j < 3072; j++){
            calibTrk2->DSPbad_par[i][j] = tempBad_par[j][i];
            calibTrk2->DSPped_par[i][j] = tempPed_par[j][i];
            calibTrk2->DSPsig_par[i][j] = tempSig_par[j][i];
        }
    }
//-----------------------------------------------------------------------------------------
    oss.str("");
    oss <<  "Fortran77 function trkcalibpkt error code = " << ERROR;
    logger->warn(oss.str().c_str());
}

