#ifndef PAMVMCFIELDMGR_H
#define PAMVMCFIELDMGR_H
#include <iostream>

#include "TString.h"

#define PAMFIELD 1


#define ZCAL   13.05  //cm
#define CALS3  10.639 //cm
#define ZSPEBP 2.97   //cm
#define HORMG  22.57  //cm

#ifdef PAMFIELD
#include "TrkParams.h"
#endif

class PamVMCFieldMgr: public TObject {

 private:

  static PamVMCFieldMgr * fm;

 protected:
  PamVMCFieldMgr() {};

 public:
  
  static PamVMCFieldMgr * Instance();


  void LoadField(){
#ifdef PAMFIELD
  // Load the PAMELA magnetic field

  std::string pamcal=getenv("PAM_CALIB"); pamcal+="/trk-param/field_param-0/";
  std::cout << "PAMELA env: " << pamcal << std::endl;
  TrkParams::SetTrackingMode();
  TrkParams::SetPrecisionFactor();
  TrkParams::SetStepMin();
  TrkParams::Set(pamcal.c_str(),1);
  TrkParams::Load(1);
#endif
  }
  
  void Field(const Double_t* x, Double_t* b) const {



#ifdef PAMFIELD
    float xm[3]={x[0],x[1],x[2]-ZCAL-CALS3-ZSPEBP-HORMG};

    b[0] = TrkParams::GetBX((float *)xm)*10;
    b[1] = TrkParams::GetBY((float *)xm)*10;
    b[2] = TrkParams::GetBZ((float *)xm)*10;
    
#else
    if(x) { 
      for (Int_t i=0; i<3; i++) b[i] = 0.0; 
    } else { 
      b[0]=b[1]=b[2]=0.0; 
    }
#endif
    
  }

  void Field(const Float_t* x, Float_t* b) const {


#ifdef PAMFIELD
    float xm[3]={x[0],x[1],x[2]-ZCAL-CALS3-ZSPEBP-HORMG};

    b[0] = TrkParams::GetBX((float *)xm)*10;
    b[1] = TrkParams::GetBY((float *)xm)*10;
    b[2] = TrkParams::GetBZ((float *)xm)*10;
    
#else
    if(x) { 
      for (Int_t i=0; i<3; i++) b[i] = 0.0; 
    } else { 
      b[0]=b[1]=b[2]=0.0; 
    }
#endif
    
  }
};

#endif
