/* ======================================================================== *\
!
! *
! * 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 06/2003 <mailto:moralejo@pd.infn.it>
!
!   Copyright: MAGIC Software Development, 2000-2003
!
!
\* ======================================================================== */

/////////////////////////////////////////////////////////////////////////////
//
// MHTrigLvl0
//
// This is intended to be a sort of "level 0 trigger display". What it really
// does is to store the number of events of a data file in which each pixel 
// has gone above a given threshold (fPixelThreshold) which is chosen when
// calling the constructor. Displaying a camera view with these values can
// help identify noisy pixels. See the macro pixfixrate.C to see an example
// of its use. Many things are to be fixed. Only inner pixels are shown now
// (which are anyhow those involved in the trigger), and the camera geometry
// (number of pixels, and how many inner ones) is not yet read from the input 
// file. 
// The "pedestal" we are using is just the signal in the first ADC slice 
// (seems reasonable from the inspection of the available test data files).
//
//
/////////////////////////////////////////////////////////////////////////////
#include "MHTrigLvl0.h"

#include <TCanvas.h>

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

#include "MParList.h"
#include "MRawEvtData.h"
#include "MRawEvtPixelIter.h"
#include "MCamDisplay.h"

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

ClassImp(MHTrigLvl0);

using namespace std;

// --------------------------------------------------------------------------
//
// Reset all pixels to 0 and reset fEntries to 0.
//
void MHTrigLvl0::Clear()
{
    fSum.Reset();
    for (int i=0; i<577; i++)
    {
        fSum.AddPixel(i, 0, 0);
        fSum[i].SetPixelUnused();
    }
    fSum.FixSize();
    fEntries = 0;
}

// --------------------------------------------------------------------------
//
// Initialize the name and title of the task.
// Resets the sum histogram
//
MHTrigLvl0::MHTrigLvl0(const Float_t pixelthreshold, 
		       const char *name, const char *title)
    : fCam(NULL), fRawEvt(NULL), fDispl(NULL)
{
    //
    //   set the name and title of this object
    //
    fName  = name  ? name  : "MHTrigLvl0";
    fTitle = title ? title : "Number of hits above per pixel";
    fPixelThreshold = pixelthreshold;

    Clear();
}

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

// --------------------------------------------------------------------------
//
// Get the event (MRawEvtData) 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 MHTrigLvl0::SetupFill(const MParList *plist)
{
    fRawEvt = (MRawEvtData*)plist->FindObject("MRawEvtData");
    if (!fRawEvt)
    {
        *fLog << dbginf << "MRawEvtData not found... aborting." << endl;
        return kFALSE;
    }

    fCam = (MGeomCam*)plist->FindObject("MGeomCam");
    if (!fCam)
        *fLog << warn << GetDescriptor() << ": No MGeomCam found." << endl;

    Clear();

    return kTRUE;
}

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

    MRawEvtPixelIter pixel(rawevt);

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

      // FIXME: number of inner pixels should be read from file
      if (pixid > 396)
	break;
      if (pixid == 0)
	continue;

      fSum[pixid].SetPixelUsed();

      //
      // FIXME: we now use as "pedestal" the value of the first ADC slice!
      //
      Float_t baseline = rawevt->GetNumHiGainSamples() *
	pixel.GetHiGainSamples()[0];

      Float_t pixel_signal = pixel.GetSumHiGainSamples() - baseline;

      Float_t pixel_is_on = ( pixel_signal > fPixelThreshold)? 1. : 0.;

      fSum[pixid].AddNumPhotons(pixel_is_on);
    }

    fEntries++;

    return kTRUE;
}

// --------------------------------------------------------------------------
//
// Set to Unused outer pixels.
//
Bool_t MHTrigLvl0::Finalize()
{
  //
  // Show only pixels in the inner region of the camera:
  // (otherwise, problem with the too different ranges) 
  //
  for (Int_t i=0; i<577; i++)
    // FIXME: read number of total and inner pixels from file
    {
      if (i > 396)
	fSum[i].SetPixelUnused();
    }

  //  fSum.Scale(fEntries); Now disabled, scale was not readable otherwise.

  return kTRUE;
}

// --------------------------------------------------------------------------
//
// Draw the present 'fill status'
//
void MHTrigLvl0::Draw(Option_t *)
{
    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);

    AppendPad("");
}

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

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

    fDispl->Fill(fSum);
    fDispl->Paint();
}
