/*
 * CaloGeomCut.cpp
 *
 *  Created on: 19-mar-2009
 *      Author: Sergio Ricciarini, Nicola Mori
 */

/*! @file CaloGeomCut.cpp The CaloCrossCut class implementation file */

#include "CaloGeomCut.h"

int CaloGeomCut::Check(PamLevel2 *event) {

  Float_t xCaloTrack = 0.;
  Float_t yCaloTrack = 0.;
  
  Double_t tanx, tany, beta;
  Float_t alCaloTop[5]; // MUST be Float_t
  Int_t nPoint = TrkParams::nGF+1; // MUST be Int_t
  Float_t zIn[nPoint]; // MUST be Float_t
  
  Trajectory* traj = NULL;
  
  static const Float_t zCaloTop=-26.181; // cm MUST Float_t

  tanx=_xCaloAxis->par[1];
  tany=_yCaloAxis->par[1];
        
  if (_iMethod==0) {
  }
  else if (_iMethod==1) { // curved track in the Pamela acceptance (back-propagated starting from the straight track in the calorimeter, evaluated at the top of calorimeter, which is of course better than at higher z coordinates)
    for (Int_t igf = 0; igf < TrkParams::nGF; igf++) {
      zIn[igf]=TrkParams::zGF[igf];
    }
    zIn[TrkParams::nGF]=zCaloTop;
    
    traj = (Trajectory*) new Trajectory(nPoint,zIn);
    
    alCaloTop[0]=_xCaloAxis->GetYfit(zCaloTop); // Yfit   [xCaloTop] 
    alCaloTop[1]=_yCaloAxis->GetYfit(zCaloTop); // Yfit  [yCaloTop]
    alCaloTop[2]=sin(atan(sqrt(pow(tanx,2)+pow(tany,2)))); // [sintheta]
    alCaloTop[3]=TMath::Pi()+atan2(tany,tanx); // [phi]

    beta = event->GetToFLevel2()->CalcBeta(0,_resMax,_qualCut,_chi2Cut); // TOF stand-alone beta
    alCaloTop[4] = 1./(_mass*beta/sqrt(1.-pow(beta,2))); // [etaP] [rho = (m/Z)*(beta/(sqrt(1-beta^2)))]

    traj->DoTrack(alCaloTop,zCaloTop);
       
  }
  else {
    return 1;
  }

  for (Int_t igf = 0; igf < TrkParams::nGF; igf++) {
      
    if (_iMethod==0) { // straight track
      // NOTE: par[0] is the x (y) coordinate on plane z=0 in PAMELA reference (magnet centre)
      xCaloTrack = _xCaloAxis->par[0] + tanx * TrkParams::zGF[igf]; // cm
      yCaloTrack = _yCaloAxis->par[0] + tany * TrkParams::zGF[igf]; // cm
    }
    else if (_iMethod==1) {
      xCaloTrack = traj->x[igf];
      yCaloTrack = traj->y[igf];
    }
    
    if (! (TrkParams::xGF_min[igf] + _xTolCaloTrack < xCaloTrack && xCaloTrack < TrkParams::xGF_max[igf]
        - _xTolCaloTrack) ) {
      return 0;
    }

    if (! (TrkParams::yGF_min[igf] + _yTolCaloTrack < yCaloTrack && yCaloTrack < TrkParams::yGF_max[igf]
        - _yTolCaloTrack) ) {
      return 0;
    }
    
  }

  return CUTOK;
  
}
