/*
 * TofDedxS1Cut.cpp
 *
 *  Created on: 13-mar-2009
 *      Author: Sergio Ricciarini, Nicola Mori
 *  Reworked on: 21-jul-2011
 *      Author: Nicola Mori, Valeria Di Felice
 */

/*! @file TofDedxS1Cut.cpp The TofDedxS1Cut class implementation file */

#include "TofDedxS1Cut.h"

int TofDedxS1Cut::Check(PamLevel2 *event) {

  int idx = 0;
  for (int i = 0; i < event->GetToFLevel2()->ntrk(); i++) {
    if (event->GetToFLevel2()->GetToFTrkVar(i)->trkseqno == event->GetTrack(0)->GetTrkTrack()->GetSeqNo())
      idx = i;
  }

  float dEdx = 0;
  int nLayers = 0;
  float dEdxLayer = event->GetToFLevel2()->GetdEdx(idx, 0, 100);

  // Patch to exclude S115b
  ToFTrkVar *tofTrk = event->GetToFLevel2()->GetToFTrkVar(idx);
  bool has8 = false, has9 = false;
  float dedx9 = 0.;
  for (Int_t ib = 0; ib < tofTrk->npmtadc; ib++) {
    if (tofTrk->pmtadc[ib] == 8) {
      has8 = true;
    }
    if (tofTrk->pmtadc[ib] == 9) {
      has9 = true;
      dedx9 = tofTrk->dedx[ib];
    }
  }

  if (has9){
    dEdxLayer -= (dedx9 / ((int) has8 + 1));
    dEdxLayer *= 2.;
  }
  //End of patch

  if (dEdxLayer > 0. && dEdxLayer < 4090) {
    dEdx += dEdxLayer;
    nLayers++;
  }
  dEdxLayer = event->GetToFLevel2()->GetdEdx(idx, 1, 100);
  if (dEdxLayer > 0. && dEdxLayer < 4090) {
    dEdx += dEdxLayer;
    nLayers++;
  }

  if (nLayers > 0) {
    dEdx /= nLayers;

    float R = event->GetTrack(0)->GetTrkTrack()->GetRigidity();

    if (dEdx >= (3.102 - 2.6 * TMath::Log(R)) * (R < 1.05) + 3. * (R >= 1.05))
      return 0;

    return CUTOK;
//    if (dEdx < (3.102 - 2.6 * TMath::Log(R)) * (R < 1.05) + 3. * (R >= 1.05))
//      return 0;
//
//    return CUTOK;
  }
  else {
    return 0;
  }

}
