/* ======================================================================== *\
!
! *
! * 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    1/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
!   Author(s): Wolfgang Wittek 1/2002 <mailto:wittek@mppmu.mpg.de>
!
!   Copyright: MAGIC Software Development, 2000-2002
!
!
\* ======================================================================== */

//////////////////////////////////////////////////////////////////////////////
//                                                                          //
//  MHAlphaEnergyTheta                                                      //
//                                                                          //
//  3D-histogram in alpha, E-est and Theta                                  //
//                                                                          //
//////////////////////////////////////////////////////////////////////////////

#include "MHAlphaEnergyTheta.h"

#include <TCanvas.h>

#include <math.h>

#include "MMcEvt.hxx"
#include "MHillasSrc.h"
#include "MEnergyEst.h"

#include "MBinning.h"
#include "MParList.h"

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

ClassImp(MHAlphaEnergyTheta);

// --------------------------------------------------------------------------
//
// Default Constructor. It sets name and title of the histogram. 
//
MHAlphaEnergyTheta::MHAlphaEnergyTheta(const char *name, const char *title)
{
    //
    //   set the name and title of this object
    //
    fName  = name  ? name  : "MHAlphaEnergyTheta";
    fTitle = title ? title : "3-D histogram in alpha, energy and theta";

    fHist.SetDirectory(NULL);

    fHist.SetTitle("3D-plot of alpha, E-est, Theta");
    fHist.SetXTitle("\\alpha [\\circ]");
    fHist.SetYTitle("E_{est} [GeV]");
    fHist.SetZTitle("\\Theta [\\circ]");
}

// --------------------------------------------------------------------------
//
// Set binnings and prepare filling of the histogram
// 
Bool_t MHAlphaEnergyTheta::SetupFill(const MParList *plist)
{
   fEnergy = (MEnergyEst*)plist->FindObject("MEnergyEst");
   if (!fEnergy)
   {
       *fLog << err << dbginf << "MEnergyEst not found... aborting." << endl;
       return kFALSE;
   }

   fMcEvt = (MMcEvt*)plist->FindObject("MMcEvt");
   if (!fMcEvt)
   {
       *fLog << err << dbginf << "MMcEvt not found... aborting." << endl;
       return kFALSE;
   }

   MBinning* binsenergy = (MBinning*)plist->FindObject("BinningE");
   MBinning* binsalpha  = (MBinning*)plist->FindObject("BinningAlpha");
   MBinning* binstheta  = (MBinning*)plist->FindObject("BinningTheta");
   if (!binsenergy || !binsalpha || !binstheta)
   {
       *fLog << err << dbginf << "At least one MBinning not found... aborting." << endl;
       return kFALSE;      
   }

   SetBinning(&fHist, binsalpha, binsenergy, binstheta);

   fHist.Sumw2(); 

   return kTRUE;
}

// --------------------------------------------------------------------------
//
// Fill the histogram
// 
Bool_t MHAlphaEnergyTheta::Fill(const MParContainer *par)
{
    MHillasSrc &hil = *(MHillasSrc*)par;

    fHist.Fill(hil.GetAlpha(), fEnergy->GetEnergy(), fMcEvt->GetTheta()*kRad2Deg);

    return kTRUE;
}

// --------------------------------------------------------------------------
//
// Draw the histogram
// 
void MHAlphaEnergyTheta::Draw(Option_t *opt)
{
    if (!gPad)
        MakeDefCanvas("AlphaEnergyTheta", fTitle);

    gPad->Divide(2,2);

    TH1 *h;

    gPad->cd(1);
    h = fHist.Project3D("expro");

    h->SetTitle("Distribution of \\alpha [\\circ]");
    h->SetXTitle("\\alpha [\\circ]");
    h->SetYTitle("Counts");

    h->Draw(opt);
    h->SetBit(kCanDelete);

    gPad->cd(2);
    h = fHist.Project3D("eypro");

    h->SetTitle("Distribution of E-est [GeV]");
    h->SetXTitle("E_{est} [GeV]");
    h->SetYTitle("Counts");

    h->Draw(opt);
    h->SetBit(kCanDelete);
    gPad->SetLogx();

    gPad->cd(3);
    h = fHist.Project3D("ezpro");

    h->SetTitle("Distribution of \\Theta [\\circ]");
    h->SetXTitle("\\Theta [\\circ]");
    h->SetYTitle("Counts");

    h->Draw(opt);
    h->SetBit(kCanDelete);

    gPad->cd(4);
    fHist.Draw(opt);

    gPad->Modified();
    gPad->Update();
}

// --------------------------------------------------------------------------
//
// Draw copies of the histogram
// 
TObject *MHAlphaEnergyTheta::DrawClone(Option_t *opt) const
{
    TCanvas &c = *MakeDefCanvas("AlphaEnergyTheta", fTitle);
    c.Divide(2, 2);

    gROOT->SetSelectedPad(NULL);

    TH1 *h;

    c.cd(1);
    h = ((TH3*)(&fHist))->Project3D("expro");

    h->SetTitle("Distribution of \\alpha [\\circ]");
    h->SetXTitle("\\alpha [\\circ]");
    h->SetYTitle("Counts");

    h->Draw(opt);
    h->SetBit(kCanDelete);

    c.cd(2);
    h = ((TH3*)(&fHist))->Project3D("eypro");

    h->SetTitle("Distribution of E-est [GeV]");
    h->SetXTitle("E-est [GeV]            ");
    h->SetYTitle("Counts");

    h->Draw(opt);
    h->SetBit(kCanDelete);
    gPad->SetLogx();

    c.cd(3);
    h = ((TH3*)(&fHist))->Project3D("ezpro");

    h->SetTitle("Distribution of \\Theta [\\circ]");
    h->SetXTitle("\\Theta [\\circ]");
    h->SetYTitle("Counts");

    h->Draw(opt);
    h->SetBit(kCanDelete);

    c.cd(4);
    ((TH3&)fHist).DrawCopy(opt);

    c.Modified();
    c.Update();

    return &c;
}

// --------------------------------------------------------------------------
//
// Calculate the histogram as the difference of two histograms :
//          fHist(gamma) = h1(source) - h2(antisource)
// 
void MHAlphaEnergyTheta::Subtract(const TH3D *h1, const TH3D *h2)
{
    // MH::SetBinning(&fHist, (TH1*)h1);

    //    fHist.Sumw2();
    fHist.Add((TH1*)h1, (TH1*)h2, 1, -1); // Root: FIXME
}


// --------------------------------------------------------------------------
//
// Integrate fHist(gamma) in the alpha range (lo, up)
// 
TH2D *MHAlphaEnergyTheta::GetAlphaProjection(Axis_t lo, Axis_t up)
{
    if (up < lo)
    {
        *fLog << err << fName << ": Alpha projection not possible: lo=" << lo << " up=" << up << endl;
        return NULL;
    }

    TAxis &axe = *fHist.GetXaxis();

    Int_t ilo = axe.FindFixBin(lo);
    Int_t iup = axe.FindFixBin(up);

    const Double_t epslo1 = lo-axe.GetBinLowEdge(ilo);
    const Double_t epslo2 = axe.GetBinUpEdge(ilo)-lo;

    const Double_t epsup1 = up-axe.GetBinLowEdge(iup);
    const Double_t epsup2 = axe.GetBinUpEdge(iup)-up;

    const Double_t epslo = epslo1<epslo2 ? epslo1 : epslo2;
    const Double_t epsup = epsup1<epsup2 ? epsup1 : epsup2;

    if (epslo1>epslo2)
        ilo++;

    if (epsup1<epsup2)
        iup--;

    if (epslo>0.01*axe.GetBinWidth(ilo) || epsup>0.01*axe.GetBinWidth(iup))
    {
        *fLog << err << fName << ": binning is not adequate for the requested projection:" << endl;
        *fLog << "Please specify a lower or upper limit which is not more than 1% away from a bin edge" << endl;
        *fLog << " epslo = " << epslo << endl;
        *fLog << " epsup = " << epsup << endl;
        *fLog << " dwl   = " << axe.GetBinWidth(ilo) << endl;
        *fLog << " dwu   = " << axe.GetBinWidth(iup) << endl;
        return NULL;
    }

    axe.SetRange(ilo, iup);

    TH2D &h2D = *(TH2D *)fHist.Project3D("ezypro");

    h2D.SetTitle("2D-plot  of Theta vs. E-est");
    h2D.SetXTitle("E-est [GeV]            ");
    h2D.SetYTitle("\\Theta [\\circ]");

    return &h2D;
}

// --------------------------------------------------------------------------
//
// Draw the integrated histogram
// 
TH2D *MHAlphaEnergyTheta::DrawAlphaProjection(Axis_t lo, Axis_t up, Option_t *opt)
{
    TH2D *h2D = GetAlphaProjection(lo, up);

    if (!h2D)
        return NULL;

    char txt[100];
    sprintf(txt, "No.of Gammas vs. E-est and Theta (%.1f < alpha < %.1f deg)", lo, up);

    //    TCanvas *c = MakeDefCanvas("AlphaEnergyTheta", "2D histogram of gamma signal in energy and theta");
    TCanvas &c = *MakeDefCanvas("AlphaEnergyTheta", txt);

    c.Divide(2, 2);

    gROOT->SetSelectedPad(NULL);

    TH1 *h;

    c.cd(1);
    h = h2D->ProjectionX("Eest", -1, 9999, "E");
    h->SetTitle("Distribution of E-est [GeV]");
    h->SetXTitle("E-est [GeV]            ");
    h->SetYTitle("Counts");

    h->Draw(opt);
    h->SetBit(kCanDelete);
    gPad->SetLogx();

    c.cd(2);
    h = h2D->ProjectionY("theta", -1, 9999, "E");
    h->SetTitle("Distribution of \\Theta [\\circ]");
    h->SetXTitle("\\Theta [\\circ]");
    h->SetYTitle("Counts");

    h->Draw(opt);
    h->SetBit(kCanDelete);

    c.cd(3);

    h2D->DrawCopy(opt);
    gPad->SetLogx();

    c.Modified();
    c.Update();

    return h2D;
}












