/* ======================================================================== *\
!
! *
! * 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): Markus Gaug   11/2003 <mailto:markus@ifae.es>
!
!   Copyright: MAGIC Software Development, 2000-2001
!
!
\* ======================================================================== */

/////////////////////////////////////////////////////////////////////////////
//                                                                         //
// MCalibrationPix                                                         //
//                                                                         //
// This is the storage container to hold informations about the pedestal   //
// (offset) value of one Pixel (PMT).                                      //
//                                                                         //
/////////////////////////////////////////////////////////////////////////////
#include "MCalibrationPix.h"

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

ClassImp(MCalibrationPix);

using namespace std;

// --------------------------------------------------------------------------
//
// Default Constructor. 
//
MCalibrationPix::MCalibrationPix(const char *name, const char *title)
    : fPixId(-1),
      fCharge(-1.),
      fErrCharge(-1.),
      fSigmaCharge(-1.),
      fErrSigmaCharge(-1.),
      fRSigmaSquare(-1.),
      fChargeProb(-1.),
      fPed(-1.),
      fPedRms(-1.),
      fTime(-1.),
      fSigmaTime(-1.),
      fTimeChiSquare(-1.),
      fFactor(1.3),
      fPheFFactorMethod(-1.),
      fConversionFFactorMethod(-1.),
      fConversionBlindPixelMethod(-1.),
      fConversionPINDiodeMethod(-1.),
      fConversionErrorFFactorMethod(-1.),
      fConversionErrorBlindPixelMethod(-1.),
      fConversionErrorPINDiodeMethod(-1.),
      fConversionSigmaFFactorMethod(-1.),
      fConversionSigmaBlindPixelMethod(-1.),
      fConversionSigmaPINDiodeMethod(-1.),
      fHiGainSaturation(kFALSE),
      fElectronicPedRms(1.5)
{

  fName  = name  ? name  : "MCalibrationPixel";
  fTitle = title ? title : "Container of the MHCalibrationPixels and the fit results";

  fHist = new MHCalibrationPixel("MHCalibrationPixel","Calibration Histograms Pixel ");

}

MCalibrationPix::~MCalibrationPix() 
{
  delete fHist;
}


void MCalibrationPix::DefinePixId(Int_t i)
{
  
  fPixId = i;
  fHist->ChangeHistId(i);
  
}


// ------------------------------------------------------------------------
//
// Invalidate values
//
void MCalibrationPix::Clear(Option_t *o)
{
  fHist->Reset();
}

Bool_t MCalibrationPix::FitCharge() 
{

  if (fHist->IsFitOK())
    return kTRUE;

  if (fPed && fPedRms)
    fHist->SetLowerFitRange(1.5*fPedRms);
  else
    *fLog << warn << "Cannot set lower fit range: Pedestals not available" << endl;

  if (fHist->UseLoGain())
    {

      SetHiGainSaturation();

      if(!fHist->FitChargeLoGain())
	{
	  *fLog << warn << "Could not fit Lo Gain charges of pixel " << fPixId << endl;
	  fHist->PrintChargeFitResult();
	  //	  return kFALSE;
	}
    }
  else 
    {
      if(!fHist->FitChargeHiGain())
	{
	  *fLog << warn << "Could not fit Hi Gain charges of pixel " << fPixId << endl;
	  fHist->PrintChargeFitResult();
	  //	  return kFALSE;
	}
    }
  

  fCharge         = fHist->GetChargeMean();
  fErrCharge      = fHist->GetChargeMeanErr(); 
  fSigmaCharge    = fHist->GetChargeSigma();
  fErrSigmaCharge = fHist->GetChargeSigmaErr();
  fChargeProb     = fHist->GetChargeProb();

  if ((fPed > 0.)  && (fPedRms > 0.))
    {
      
      Float_t pedrmssquare = fPedRms*fPedRms;
      Float_t sigmasquare  = fSigmaCharge*fSigmaCharge;

      if (fHiGainSaturation)
	{
          
          Float_t logainrmssquare = fElectronicPedRms*fElectronicPedRms;
          Float_t nsbsquare       = pedrmssquare - logainrmssquare;
	  //	  Float_t logainrms = fElectronicPedRms + (TMath::Sqrt(fPedRms*fPedRms - fElectronicPedRms*fElectronicPedRms));

	  if (nsbsquare > 0.)
	      logainrmssquare = nsbsquare/100. + logainrmssquare;

          fRSigmaSquare = sigmasquare - logainrmssquare;

          if (fRSigmaSquare > 0.)
            fPheFFactorMethod = fFactor*(fCharge*fCharge/100.) / fRSigmaSquare;

	}
      else  /* if (fHiGainSaturation) */
        {
          fRSigmaSquare = sigmasquare - pedrmssquare;
          fPheFFactorMethod   =  fFactor * fCharge*fCharge / fRSigmaSquare;
        }
      

      if (fCharge > 0.)
       fConversionFFactorMethod  =  fPheFFactorMethod /  fCharge ;

      else  
	*fLog << warn << "Cannot apply F-Factor method: Reduced Sigmas are smaller than 0 in pixel: " 
	      << fPixId << endl;

    } /*   if ((fPed > 0.)  && (fPedRms > 0.)) */

  return kTRUE;
  
}


void MCalibrationPix::SetPedestal(Float_t ped, Float_t pedrms)
{

  fPed    = ped;    
  fPedRms = pedrms;
  
}

Bool_t MCalibrationPix::FitTime() 
{

  if (fHiGainSaturation)
    {
      if(!fHist->FitTimeLoGain())
	{
	  *fLog << warn << "Could not fit Lo Gain times of pixel " << fPixId << endl;
	  fHist->PrintTimeFitResult();
	  return kFALSE;
	}
    }
  else
    {
      if(!fHist->FitTimeHiGain())
	{
	  *fLog << warn << "Could not fit Hi Gain times of pixel " << fPixId << endl;
	  fHist->PrintTimeFitResult();
	  return kFALSE;
	}
    }
    
  fTime          = fHist->GetTimeMean();
  fSigmaTime     = fHist->GetTimeSigma();
  fTimeChiSquare = fHist->GetTimeChiSquare();

  return kTRUE;
}

