/* ======================================================================== *\
!
! *
! * 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-2004
!
!
\* ======================================================================== */

/////////////////////////////////////////////////////////////////////////////
//                                                               
// MCalibrationRelTimeCam                                               
//                                                               
// Hold the whole Calibration results of the camera:
//                                                               
// 1) MCalibrationRelTimeCam initializes a TClonesArray whose elements are 
//    pointers to MCalibrationRelTimePix Containers
//
// The calculated values (types of GetPixelContent) are:
// 
// Fitted values:
// ============== 
//
// 0: Fitted RelTime
// 1: Error of fitted RelTime
// 2: Sigma of fitted RelTime
// 3: Error of Sigma of fitted RelTime
//
// Useful variables derived from the fit results:
// =============================================
//
// 4: Returned probability of Gauss fit to RelTime distribution
//
/////////////////////////////////////////////////////////////////////////////
#include "MCalibrationRelTimeCam.h"
#include "MCalibrationCam.h"

#include <TClonesArray.h>

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

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

#include "MCalibrationRelTimePix.h"

ClassImp(MCalibrationRelTimeCam);

using namespace std;

// --------------------------------------------------------------------------
//
// Default constructor. 
//
// Creates a TClonesArray of MCalibrationPix containers, initialized to 1 entry
// Later, a call to MCalibrationRelTimeCam::InitSize(Int_t size) has to be performed
//
// Creates an MCalibrationBlindPix container 
//
MCalibrationRelTimeCam::MCalibrationRelTimeCam(const char *name, const char *title)
{
    fName  = name  ? name  : "MCalibrationRelTimeCam";
    fTitle = title ? title : "Storage container for the Calibration Information in the camera";

    fPixels           = new TClonesArray("MCalibrationRelTimePix",1);
    fAverageAreas     = new TClonesArray("MCalibrationRelTimePix",1);
    fAverageSectors   = new TClonesArray("MCalibrationRelTimePix",1);

    Clear();

}



// --------------------------------------
//
void MCalibrationRelTimeCam::Clear(Option_t *o)
{

  MCalibrationCam::Clear();

  CLRBIT(fFlags,kValid);

  return;
}

void MCalibrationRelTimeCam::SetValid(const Bool_t b)
{
    b ? SETBIT(fFlags, kValid) : CLRBIT(fFlags, kValid); 
}


Bool_t  MCalibrationRelTimeCam::IsValid()   const
{
  return TESTBIT(fFlags,kValid);
}

// --------------------------------------------------------------------------
//
// Print first the well fitted pixels 
// and then the ones which are not FitValid
//
void MCalibrationRelTimeCam::Print(Option_t *o) const
{

  *fLog << all << GetDescriptor() << ":" << endl;
  int id = 0;
  
  *fLog << all << "Calibrated pixels:" << endl;
  *fLog << all << endl;

  TIter Next(fPixels);
  MCalibrationRelTimePix *pix;
  while ((pix=(MCalibrationRelTimePix*)Next()))
    {
      
      if (!pix->IsExcluded()) 
	{                            

          *fLog << all 
                << Form("%s%4i%s%4.2f%s%4.2f%s%4.2f%s%4.2f","Pix  ",pix->GetPixId(),
                        ":            Offset: ",pix->GetTimeOffset()," +- ",pix->GetTimeOffsetErr(),
                        "   Precision: ",pix->GetTimePrecision()," +- ",pix->GetTimePrecisionErr())
		<< endl;
          id++;
	}
    }
  
  *fLog << all << id << " pixels" << endl;
  id = 0;
  
   
  *fLog << all << endl;
  *fLog << all << "Excluded pixels:" << endl;
  *fLog << all << endl;
  
  id = 0;

  TIter Next4(fPixels);
  while ((pix=(MCalibrationRelTimePix*)Next4()))
  {
      if (pix->IsExcluded())
      {
	  *fLog << all << pix->GetPixId() << endl;
	  id++;
      }
  }
  *fLog << all << id << " Excluded pixels " << endl;
  *fLog << endl;

  TIter Next5(fAverageAreas);
  while ((pix=(MCalibrationRelTimePix*)Next5()))
  {
    *fLog << all 
          << Form("%s%4i%s%4.2f%s%4.2f%s%4.2f%s%4.2f","Average Area   ",pix->GetPixId(),
                  ":  Offset: ",pix->GetTimeOffset()," +- ",pix->GetTimeOffsetErr(),
                  "   Precision: ",pix->GetTimePrecision()," +- ",pix->GetTimePrecisionErr())
          << endl;
  }

  TIter Next6(fAverageSectors);
  while ((pix=(MCalibrationRelTimePix*)Next5()))
  {
    *fLog << all 
          << Form("%s%4i%s%4.2f%s%4.2f%s%4.2f%s%4.2f","Average Sector ",pix->GetPixId(),
                  ":  Offset: ",pix->GetTimeOffset()," +- ",pix->GetTimeOffsetErr(),
                  "   Precision: ",pix->GetTimePrecision()," +- ",pix->GetTimePrecisionErr())
          << endl;
  }
}


// --------------------------------------------------------------------------
//
// The types are as follows:
// 
// Fitted values:
// ============== 
//
// 0: Fitted RelTime
// 1: Error of fitted RelTime
// 2: Sigma of fitted RelTime
// 3: Error of Sigma of fitted RelTime
//
// Useful variables derived from the fit results:
// =============================================
//
// 4: Returned probability of Gauss fit to RelTime distribution
//
Bool_t MCalibrationRelTimeCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
{

  if (idx > GetSize())
    return kFALSE;

  Float_t area = cam[idx].GetA();

 if (area == 0)
    return kFALSE;

 MCalibrationRelTimePix &pix = (MCalibrationRelTimePix&)(*this)[idx];

  switch (type)
    {
    case 0:
      if (pix.IsExcluded())
        return kFALSE;
      val = pix.GetMean();
      break;
    case 1:
      if (pix.IsExcluded())
        return kFALSE;
      val = pix.GetMeanErr();
      break;
    case 2:
      if (pix.IsExcluded())
        return kFALSE;
      val = pix.GetSigma();
      break;
    case 3:
      if (pix.IsExcluded())
        return kFALSE;
      val = pix.GetSigmaErr();
      break;
    case 4:
      if (pix.IsExcluded())
        return kFALSE;
      val = pix.GetProb();
      break;
    default:
      return kFALSE;
    }

  return val!=-1.;

}

// --------------------------------------------------------------------------
//
// What MHCamera needs in order to draw an individual pixel in the camera
//
void MCalibrationRelTimeCam::DrawPixelContent(Int_t idx) const
{
  (*this)[idx].DrawClone();
}



Bool_t MCalibrationRelTimeCam::GetConversion(Int_t ipx, Float_t &mean, Float_t &err, Float_t &sigma)
{

  MCalibrationRelTimePix &pix = (MCalibrationRelTimePix&)(*this)[ipx];

  mean  = pix.GetMeanConversion();
  err   = pix.GetConversionErr();
  sigma = pix.GetSigmaConversion();

  return kTRUE;
}


