/* ======================================================================== *\
!
! *
! * This file is part of MARS, the MAGIC Analysis and Reconstruction
! * Software. It is distributed to you in the hope that it can be a useful
! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
! * It is distributed WITHOUT ANY WARRANTY.
! *
! * Permission to use, copy, modify and distribute this software and its
! * documentation for any purpose is hereby granted without fee,
! * provided that the above copyright notice appear in all copies and
! * that both that copyright notice and this permission notice appear
! * in supporting documentation. It is provided "as is" without express
! * or implied warranty.
! *
!
!
!   Author(s): Abelardo Moralejo 7/2002  <mailto:moralejo@pd.infn.it>
!   Author(s): Thomas Bretz 2002  <mailto:tbretz@astro.uni-wuerzburg.de>
!
!   Copyright: MAGIC Software Development, 2002-2003
!
!
\* ======================================================================== */

//////////////////////////////////////////////////////////////////////////////
//
//   MCerPhotCalc
//
//   This is a task which calculates the number of photons from the FADC
//   time slices. It weights the each slice according to the numbers in
//   the array fWeight (default: all slices added up with weight 1).
//
//   The weights are rescaled, such that sum(weigths)=num slices
//
//  Input Containers:
//   MRawEvtData
//   MPedestalCam
//   [MRawRunHeader]
//
//  Output Containers:
//   MCerPhotEvt
//
//////////////////////////////////////////////////////////////////////////////
#include "MCerPhotCalc.h"

#include "MParList.h"

#include "MLog.h"
#include "MLogManip.h"

#include "MGeomCam.h"
#include "MMcRunHeader.hxx"

#include "MRawRunHeader.h"
#include "MRawEvtData.h"       // MRawEvtData::GetNumPixels
#include "MCerPhotEvt.h"
#include "MPedestalPix.h"
#include "MPedestalCam.h"
#include "MRawEvtPixelIter.h"

ClassImp(MCerPhotCalc);

using namespace std;

// --------------------------------------------------------------------------
//
// Default constructor.
//
MCerPhotCalc::MCerPhotCalc(const char *name, const char *title)
{
    fName  = name  ? name  : "MCerPhotCalc";
    fTitle = title ? title : "Calculate pixel signal from FADC data";

    AddToBranchList("MRawEvtData.fHiGainPixId");
    AddToBranchList("MRawEvtData.fLoGainPixId");
    AddToBranchList("MRawEvtData.fHiGainFadcSamples");
    AddToBranchList("MRawEvtData.fLoGainFadcSamples");

    SetDefaultWeights();
}

// --------------------------------------------------------------------------
//
// The PreProcess searches for the following input containers:
//  - MRawRunHeader
//  - MRawEvtData
//  - MPedestalCam
//
// The following output containers are also searched and created if
// they were not found:
//  - MCerPhotEvt
//
Int_t MCerPhotCalc::PreProcess(MParList *pList)
{
    fRunHeader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
    if (!fRunHeader)
    {
        *fLog << err << "MRawRunHeader not found... aborting." << endl;
        return kFALSE;
    }

    fRawEvt = (MRawEvtData*)pList->FindObject(AddSerialNumber("MRawEvtData"));
    if (!fRawEvt)
    {
        *fLog << err << "MRawEvtData not found... aborting." << endl;
        return kFALSE;
    }

    fPedestals = (MPedestalCam*)pList->FindCreateObj(AddSerialNumber("MPedestalCam"));
    if (!fPedestals)
    {
        *fLog << err << "MPedestalCam not found... aborting." << endl;
        return kFALSE;
    }

    fCerPhotEvt = (MCerPhotEvt*)pList->FindCreateObj(AddSerialNumber("MCerPhotEvt"));
    if (!fCerPhotEvt)
        return kFALSE;

    // Calculate sum and quadratic sum of weights:
    fSumWeights = 0;
    fSumQuadWeights = 0;
    for (Int_t i=0; i<fWeight.GetSize(); i++)
      {
	fSumWeights += fWeight[i];
	fSumQuadWeights += fWeight[i]*fWeight[i];
      }

    fSumQuadWeights = sqrt(fSumQuadWeights);

    return kTRUE;
}

// --------------------------------------------------------------------------
//
// Check for the run type and camera version.
// If the file is a MC file and the used camera version is <= 40
// we enable a fix for truncated pedestal means in this version.
//
Bool_t MCerPhotCalc::ReInit(MParList *pList)
{
    const MRawRunHeader *runheader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
    if (!runheader)
    {
        *fLog << warn << dbginf << "Warning - cannot check file type, MRawRunHeader not found." << endl;
        return kTRUE;
    }

    if (fRunHeader->GetNumSamplesHiGain() != fWeight.GetSize())
    {
        *fLog << dbginf << "Number of FADC slices (" << fRunHeader->GetNumSamplesHiGain() <<") is different from assumed one (" << fWeight.GetSize() << ")... aborting." << endl;
        return kFALSE;
    }

    Bool_t fIsMcFile = runheader->GetRunType() == kRTMonteCarlo;
    if (!fIsMcFile)
        return kTRUE;

    MMcRunHeader *mcrunheader = (MMcRunHeader*)pList->FindObject("MMcRunHeader");
    if (!mcrunheader)
    {
        *fLog << warn << dbginf << "Warning - cannot check for camera version, MC run header not found." << endl;
        return kTRUE;
    }

    fEnableFix = kFALSE;

    if (mcrunheader->GetCamVersion() <= 40)
        fEnableFix = kTRUE;

    ScalePedestals();

    return kTRUE;
}

void MCerPhotCalc::ScalePedestals()
{
    const Int_t n = fPedestals->GetSize();

    for (int idx=0; idx<n; idx++)
    {
        MPedestalPix &ped = (*fPedestals)[idx];

	// This converts the pedestal info contained in ped  from the pedestal 
	// of each FADC slice to the pedesal of the pixel signal (depends on
	// how many FADC slices are added up).

        const Double_t offset = fEnableFix ? ped.GetPedestal()-0.5 : ped.GetPedestal();

        ped.Set(offset*fSumWeights, ped.GetPedestalRms()*fSumQuadWeights);
    }

    fPedestals->SetReadyToSave();
}

// --------------------------------------------------------------------------
//
// Calculate the integral of the FADC time slices and store them as a new
// pixel in the MCerPhotEvt container.
//
Int_t MCerPhotCalc::Process()
{
    //fCerPhotEvt->InitSize(fRawEvt->GetNumPixels());

//    if (fIsMcFile)
//        ScalePedestals();

    const Int_t n = fWeight.GetSize();

    MRawEvtPixelIter pixel(fRawEvt);

    Int_t saturatedpixels = 0;

    while (pixel.Next())
    {
        const UInt_t idx = pixel.GetPixelId();

        MPedestalPix &ped = (*fPedestals)[idx];

        //
        // Calculate pixel signal unless it has all FADC slices empty:
        //
        Byte_t *ptr = pixel.GetHiGainSamples();

        Int_t i;
        Double_t nphot = 0;
        for (i=0; i<n; i++)
        {
            if (ptr[i]==0xff)
                break;
            nphot += ptr[i]*fWeight[i];
        }

	Bool_t saturatedlg = kFALSE;

        if (i<n)
        {
	    nphot = 0;

            ptr = pixel.GetLoGainSamples();
            if (ptr==NULL)
            {
                *fLog << warn << "WARNING - Pixel #" << idx << " saturated but has no lo gains... skipping!" << endl;
                return kCONTINUE;
            }

            for (i=0; i<n; i++)
            {
                if (ptr[i]==0xff)
                    saturatedlg = kTRUE;

                nphot += ptr[i]*fWeight[i];
            }

            nphot -= ped.GetPedestal();
            nphot *= 10;
        }
        else
            nphot -= ped.GetPedestal();

        fCerPhotEvt->AddPixel(idx, nphot, 0);

	if (saturatedlg)
	  saturatedpixels++;
    }

    if (saturatedpixels>0)
        *fLog << warn << "WARNING: " << saturatedpixels << " pixel(s) had saturating low gains..." << endl;

    fCerPhotEvt->FixSize();
    fCerPhotEvt->SetReadyToSave();

    return kTRUE;
}

// --------------------------------------------------------------------------
//
// Set default values for the number of slices and weights:
//
void MCerPhotCalc::SetDefaultWeights()
{
    const Float_t dummy[15] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
    fWeight.Set(15, dummy);
}
