#include "TMHistogrammingFastorInnerVsOuter.h"
#include "AliITSRawStreamSPD.h"
#include <TStyle.h>
#include <TPad.h>
#include <TH2F.h>

//_____________________________________________________________________
TMHistogrammingFastorInnerVsOuter::TMHistogrammingFastorInnerVsOuter() :
  TMHistogramming(), fRangeX(50), fRangeY(50)
{
  CreateHisto();
}
//_____________________________________________________________________
TMHistogrammingFastorInnerVsOuter::~TMHistogrammingFastorInnerVsOuter() {
  delete fTheHisto;
}
//_____________________________________________________________________
void TMHistogrammingFastorInnerVsOuter::CreateHisto() {
  fTheHisto = new TH2F("FastorInnerVsOuter", "FastOR Signals Per Event (Inner Layer vs Outer Layer)", 50, -0.5, 49.5, 50, -0.5, 49.5);
  fTheHisto->SetMinimum(0);
  fTheHisto->SetStats(0);
  fTheHisto->GetXaxis()->SetTitle("N Signals Inner Layer");
  fTheHisto->GetYaxis()->SetTitle("N Signals Outer Layer");
  fTheHisto->SetTitleOffset(1.2,"X");
  fTheHisto->SetTitleOffset(1.6,"Y");
  fTheHisto->SetBit(TH1::kCanRebin);
}
//_____________________________________________________________________
void TMHistogrammingFastorInnerVsOuter::EndEvent(AliITSRawStreamSPD *str, UInt_t globalEventNumber) {
  if (fEventAccept) {
    UInt_t totalSignalsInner = 0;
    UInt_t totalSignalsOuter = 0;
    for (UInt_t eq=0; eq<20; eq++) {
      for (UInt_t hs=0; hs<6; hs++) {
	for (UInt_t chip=0; chip<10; chip++) {
	  if (str->GetFastOrSignal(eq,hs,chip)) {
	    if (hs<2) totalSignalsInner++;
	    else      totalSignalsOuter++;
	  }
	}
      }
    }

    if ((Int_t)totalSignalsInner >= fRangeX) {
      while ((Int_t)totalSignalsInner >= fRangeX) {
	fRangeX*=2;
      }
      RebinHisto();
    }
    if ((Int_t)totalSignalsOuter >= fRangeY) {
      while ((Int_t)totalSignalsOuter >= fRangeY) {
	fRangeY*=2;
      }
      RebinHisto();
    }

    fTheHisto->Fill(totalSignalsInner,totalSignalsOuter);
  }

  TMHistogramming::EndEvent(str, globalEventNumber);
}
//_____________________________________________________________________
void TMHistogrammingFastorInnerVsOuter::Draw(TPad *pad) {
  pad->cd();
  pad->SetLeftMargin(0.15);
  pad->SetRightMargin(0.15);
  pad->SetBorderSize(0);
  pad->SetBorderMode(0);

  fTheHisto->Draw("colz");

  fNeedRedraw = kFALSE;
}
//_____________________________________________________________________
void TMHistogrammingFastorInnerVsOuter::Reset() {
  fRangeX=50;
  fRangeY=50;

  delete fTheHisto;

  CreateHisto();

  fNeedRedraw = kTRUE;

  TMHistogramming::Reset();
}
//_____________________________________________________________________
void TMHistogrammingFastorInnerVsOuter::RebinHisto() {
  fTheHisto->RebinAxis((Double_t)fRangeX,fTheHisto->GetXaxis());
  fTheHisto->RebinAxis((Double_t)fRangeY,fTheHisto->GetYaxis());
}
