/* ======================================================================== *\
!
! *
! * 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): Thomas Bretz  12/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
!
!   Copyright: MAGIC Software Development, 2000-2003
!
!
\* ======================================================================== */

/////////////////////////////////////////////////////////////////////////////
//
// MHCurrents
//
/////////////////////////////////////////////////////////////////////////////
#include "MHCurrents.h"

#include <TCanvas.h>

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

#include "MParList.h"
#include "MBinning.h"
#include "MCurrents.h"
#include "MCamDisplay.h"

#include "MGeomCam.h"
#include "MGeomPix.h"

ClassImp(MHCurrents);

using namespace std;

// --------------------------------------------------------------------------
//
// Reset all pixels to 0 and reset fEntries to 0.
//
void MHCurrents::Clear(const Option_t *)
{
    const Int_t n = fCam ? fCam->GetNumPixels() : 577;

    // FIXME: Implement a clear function with setmem
    fSum.Set(n); // also clears memory
    fRms.Set(n);
/*    for (int i=0; i<577; i++)
    {
        fSum[i] = 0;
        fRms[i] = 0;
    }*/

    fEntries = 0;
}

// --------------------------------------------------------------------------
//
// Initialize the name and title of the task.
// Resets the sum histogram
//
MHCurrents::MHCurrents(const char *name, const char *title)
    : /*fSum(577), fRms(577), */fCam(NULL), fEvt(NULL), fDispl(NULL)
{
    //
    //   set the name and title of this object
    //
    fName  = name  ? name  : "MHCurrents";
    fTitle = title ? title : "Average of MCurrents";

    Clear();

    fHist.SetName("currents;avg");
    fHist.SetTitle("Avg.Currents [nA]");
    fHist.SetXTitle("Pixel Index");
    fHist.SetYTitle("A [nA]");
    fHist.SetDirectory(NULL);
    fHist.SetLineColor(kGreen);
    fHist.SetMarkerStyle(kFullDotMedium);
    fHist.SetMarkerSize(0.3);
}

// --------------------------------------------------------------------------
//
// Delete the corresponding camera display if available
//
MHCurrents::~MHCurrents()
{
    if (fDispl)
        delete fDispl;
}

// --------------------------------------------------------------------------
//
// Get the event (MCerPhotEvt) the histogram might be filled with. If
// it is not given, it is assumed, that it is filled with the argument
// of the Fill function.
// Looks for the camera geometry MGeomCam and resets the sum histogram.
//
Bool_t MHCurrents::SetupFill(const MParList *plist)
{
    fEvt = (MCurrents*)plist->FindObject("MCurrents");
    if (!fEvt)
        *fLog << warn << GetDescriptor() << ": No MCerPhotEvt available..." << endl;

    fCam = (MGeomCam*)plist->FindObject("MGeomCam");
    /*
    if (!fCam)
        *fLog << warn << GetDescriptor() << ": No MGeomCam found... assuming Magic geometry!" << endl;
    */
    if (!fCam)
    {
        *fLog << err << GetDescriptor() << ": No MGeomCam found... aborting." << endl;
        return kFALSE;
    }

    Clear();

    const Int_t n = fSum.GetSize();

    MBinning bins;
    bins.SetEdges(n, -0.5, n-0.5);
    bins.Apply(fHist);

    return kTRUE;
}

// --------------------------------------------------------------------------
//
// Fill the histograms with data from a MCerPhotEvt-Container.
//
Bool_t MHCurrents::Fill(const MParContainer *par, const Stat_t w)
{
    const MCurrents *evt = par ? (MCurrents*)par : fEvt;
    if (!evt)
    {
        *fLog << err << dbginf << "No MCurrents found..." << endl;
        return kFALSE;
    }

    const Int_t n = fSum.GetSize();
    for (UInt_t idx=0; idx<n; idx++)
    {
        Float_t val;
        if (!evt->GetPixelContent(val, idx))
            continue;

        fSum[idx] += val;
        fRms[idx] += val*val;

    }

    fEntries++;

    return kTRUE;
}

// --------------------------------------------------------------------------
//
// Scale the sum container with the number of entries
//
Bool_t MHCurrents::Finalize()
{
    if (fEntries<2)
    {
        *fLog << warn << "WARNING - " << GetDescriptor() << " doesn't contain enough entries." << endl;
        return kTRUE;
    }

    const Int_t n = fSum.GetSize();
    for (UInt_t i=0; i<n; i++)
    {
        // calc sdev^2 for pixel index i
        // var^2 = (sum[xi^2] - sum[xi]^2/n) / (n-1);
        fRms[i] -= fSum[i]*fSum[i]/fEntries;
        fRms[i] /= fEntries-1;

        if (fRms[i]<0)
        {
            *fLog << warn << "WARNING - fRms[" << i <<"]= " << fRms[i] << " -> was set to 0 " << endl;
            fRms[i]=0;
        }

        else
            fRms[i]  = TMath::Sqrt(fRms[i]);

        // calc mean value for pixel index i
        fSum[i] /= fEntries;

        fHist.SetBinContent(i+1, fSum[i]);
        fHist.SetBinError(  i+1, fRms[i]);
    }
    return kTRUE;
}

// --------------------------------------------------------------------------
//
// Draw the present 'fill status'
//
void MHCurrents::Draw(Option_t *o)
{
    if (!fCam)
    {
        *fLog << warn << "WARNING - Cannot draw " << GetDescriptor() << ": No Camera Geometry available." << endl;
        return;
    }

    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this, 750, 600);
    pad->SetBorderMode(0);

    SetDrawOption(o);
    AppendPad("");
}

// --------------------------------------------------------------------------
//
// If a camera display is not yet assigned, assign a new one.
//
void MHCurrents::Paint(Option_t *option)
{
    if (!fCam)
    {
        *fLog << warn << "WARNING - Cannot paint " << GetDescriptor() << ": No Camera Geometry available." << endl;
        return;
    }

    if (!fDispl)
        fDispl = new MCamDisplay(fCam);

    TString opt(GetDrawOption());

    fDispl->Fill(opt.Contains("rms", TString::kIgnoreCase) ? fRms : fSum);
    fDispl->Paint();
}
