#include "TMHistogrammingGlobalPixelPhiDistRef.h"
#include "TMControlSPD.h"
#include "AliITSRawStreamSPD.h"
#include <TStyle.h>
#include <TPad.h>
#include <TH1F.h>
#include <TMath.h>

//_____________________________________________________________________
TMHistogrammingGlobalPixelPhiDistRef::TMHistogrammingGlobalPixelPhiDistRef() :
  TMHistogramming()
{ 

  fTotal = new TH1F("GlobalPixelPhiDistRefTotal","Global Phi Distribution Ref (black=all, red=outer, blue=inner layer)",200,-3.15,3.15);
  fTotal->SetLineColor(kBlack);
  fTotal->GetXaxis()->SetTitle("Phi [rad]");
  fTotal->SetStats(0);

  fInner = new TH1F("GlobalPixelPhiDistRefInner","Global Phi Distribution Ref (black=all, red=outer, blue=inner layer)",200,-3.15,3.15);
  fInner->SetLineColor(kBlue);
  fInner->GetXaxis()->SetTitle("Phi [rad]");
  fInner->SetStats(0);

  fOuter = new TH1F("GlobalPixelPhiDistRefOuter","Global Phi Distribution Ref (black=all, red=outer, blue=inner layer)",200,-3.15,3.15);
  fOuter->SetLineColor(kRed);
  fOuter->GetXaxis()->SetTitle("Phi [rad]");
  fOuter->SetStats(0);
}
//_____________________________________________________________________
TMHistogrammingGlobalPixelPhiDistRef::~TMHistogrammingGlobalPixelPhiDistRef() {
  delete fTotal;
  delete fInner;
  delete fOuter;
}
//_____________________________________________________________________
void TMHistogrammingGlobalPixelPhiDistRef::EndEvent(AliITSRawStreamSPD *str, UInt_t globalEventNumber) {
  if (fEventAccept) {
    if (fNrEvents==0) {
      UInt_t mod, colM, rowM;
      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->IsActiveChip(eq,hs,chip)) {
	      UInt_t col=0;
	      for (UInt_t row=0; row<256; row++) {
		AliITSRawStreamSPD::OnlineToOffline(eq,hs,chip,col,row,mod,colM,rowM);
		TMControlSPD::Instance()->TransformClusterToGlobal(mod,colM,rowM);  
		Float_t x = TMControlSPD::Instance()->GetGlobalX();
		Float_t y = TMControlSPD::Instance()->GetGlobalY();
		Float_t phi = atan2(y,x);
		fTotal->Fill(phi,32);
		if (hs<2) fInner->Fill(phi,32);
		else      fOuter->Fill(phi,32);
	      }
	    }
	  }
	}
      }
    }
  }

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

  fTotal->Draw();
  fInner->Draw("same");
  fOuter->Draw("same");
}
//_____________________________________________________________________
void TMHistogrammingGlobalPixelPhiDistRef::Reset() {
  fTotal->Reset();
  fInner->Reset();
  fOuter->Reset();
  TMHistogramming::Reset();
}


