#include "MCalcPed1.h"

#include <stdlib.h>

#include <TROOT.h> 
#include <TApplication.h> 
#include <TSystem.h> 
#include <TGClient.h> 
#include <TGFileDialog.h> 
#include <TVirtualX.h>

#include "MRawEvt.h"
#include "MParList.h"
#include "MHistosAdc.h"


////////////////////////////////////////////////////////////////////////
//
//  MGShowSpect.h
//
//  A Gui Task to show the raw ADC values in the histograms
//

ClassImp(MCalcPed1)
  

Bool_t MCalcPed1::PreProcess(MParList *pList)
{
  //
  //   Do the preprocessing for MCalcPed1
  // 
  //   Connects Histogramms in the MHistosAdc container as the input
  //   and the MPedest class in the list for output
  //

  fHists = (MHistosAdc*) pList->FindObject("MHistosAdc");
  
  if (!fHists)
    {
      cout << "ERROR: MCalcPed1::PreProc():  MHistosAdc  not found!" << endl;
      exit(1);
    }
  
  fPedData = (MPedest*) pList->FindObject("MPedest");
  
  if (!fPedData)
    {
      cout << "ERROR: MCalcPed1::PreProc(): MPedest   not found!" << endl;
      exit(1);
    }
  
  return (kTRUE) ; 
} 


Bool_t MCalcPed1::PostProcess()
{
  //   just start the gui for displaying the adc spectra


  //  loop over the high gain histograms and do a fit to them to get
  //  the pedestal datas

  //   define the function to fit

  TH1F *histofit ; 
  TF1  *gausfit = new TF1 ("gausfit", "gaus", 0., 100.  )  ; 
  
  TObjArray  *histList ; 

  Int_t iEnt ; 

  //  all for the high gains 
  
  histList = fHists->GetHighList() ; 
  for ( Int_t i=0; i< fHists->GetHighEntries() ; i++ ) { 
    
    //   select the histogram
    histofit = (TH1F*) histList->At(i) ; 
    iEnt = histofit->GetEntries() ; 

    if ( iEnt  > 1. ) { 
      histofit->Fit("gausfit", "RQN" ) ;
      fPedData->SetAllHigh(i, 
			   gausfit->GetParameter(1), gausfit->GetParameter(1)/sqrt(iEnt-1.) , 
			   gausfit->GetParameter(2), gausfit->GetParameter(2)/sqrt(2. * iEnt ) ) ; 
    } 
    else { 
      fPedData->SetAllHigh(i, -1., -1., -1., -1. ) ; 
    } 
  } 

   //  all for the low gains 
  
  histList = fHists->GetLowList() ; 
  for ( Int_t i=0; i< fHists->GetLowEntries() ; i++ ) { 
    
    histofit = (TH1F*) histList->At(i) ; 
    iEnt = histofit->GetEntries() ; 

    if ( iEnt  > 1. ) { 
      histofit->Fit("gausfit", "RQN" ) ;
      
      fPedData->SetAllLow(i, 
			  gausfit->GetParameter(1), gausfit->GetParameter(1)/sqrt(iEnt-1.) , 
			  gausfit->GetParameter(2), gausfit->GetParameter(2)/sqrt(2. * iEnt ) ) ; 
    } 
    else { 
      fPedData->SetAllLow(i, -1., -1., -1., -1. ) ; 
    } 
  } 

  
  
  //  fPedData->Print() ; 

  
    if (strcmp (fFileOut, "nooutput"))
    {
        //
        //   write the histograms to File
        //
        cout << endl << "--> INFO: write the histograms to file: "
            << fFileOut  << endl ;

   
	TFile out( fFileOut, "recreate") ;

	//
	//  write the pedestal container to file
	//
	
	fPedData->Write() ;
	
	out.Close() ; 
    }


  return (kTRUE) ; 
} 










