#ifndef PAMVMCTRKF77_H
#define PAMVMCTRKF77_H

#define grndmc GRNDMC
#define gmtod GMTODC
#define gdtom GDTOMC
#define gufield GUFIELD
#define errfcc ERRFCC
#define vzeroi VZEROI
#define vzeroc VZEROC

#include <iostream>

using std::cout;
using std::endl; 
#include <TGeoManager.h>
#include <TGeoMatrix.h>
#include <TVirtualMC.h>
#include <TRandom.h>
#include <TMath.h>
#include "PamVMCFieldMgr.h"
#include "PamVMCRndMgr.h"
extern "C"{
  void grndmc_(Float_t*, Int_t& );
  void gmtodc_(Float_t* , Float_t* , Int_t& );
  void gdtomc_(Float_t* , Float_t* , Int_t& );
  void gufield_(Float_t*, Float_t*);
  void errfcc_(Float_t&, Float_t&);
  void vzeroi_(Int_t*,Int_t&);
  void vzeroc_(Float_t*, Int_t&);
 }

void grndmc_(Float_t* r, Int_t& n){
  for (Int_t i=0; i<n; i++){
    r[i] = (Float_t)PamVMCRndMgr::Instance()->GenRandom("TRKEXT");
  }
}

void gmtodc_(Float_t* a, Float_t* b, Int_t& c){
  Double_t master[3];
  Double_t local[3];

  for (Int_t i=0; i<3; ++i)  master[i] = (Double_t) a[i];
  
  Double_t * m = &master[0];
  Double_t * l = &local[0];
  
  gGeoManager->MasterToLocal(m,l);

  //cout<<"MasterToLocal"<<endl;
  for (Int_t i=0; i<3; ++i){
    //cout<<master[i]<<" "<<local[i]<<endl;
    b[i] = (Float_t)local[i];
  }
  //c=c;
}


void gdtomc_(Float_t* a, Float_t* b, Int_t& c){
  Double_t master[3];
  Double_t local[3];

  for (Int_t i=0; i<3; ++i) local[i] = (Double_t)a[i];
  
  Double_t * m = &master[0];
  Double_t * l = &local[0];

  gGeoManager->LocalToMaster(l,m);

  //cout<<"LocalToMaster"<<endl;
  for (Int_t i=0; i<3; ++i) {
    //cout<<" "<<local[i]<<" "<<master[i]<<endl;
    b[i] = (Float_t)master[i];
  }
  //c=c;
}

void gufield_(Float_t *x, Float_t *b){
  PamVMCFieldMgr::Instance()->Field(x,b);
}

void errfcc_(Float_t& in, Float_t& out){
  out = (Float_t)TMath::Erfc(in);
}

void vzeroi_(Int_t* arr,Int_t& n){
  for(Int_t i=0; i<n; i++) arr[i] = 0;
}

void vzeroc_(Float_t* arr,Int_t& n){
  for(Int_t i=0; i<n; i++) arr[i] = 0.;
}

#endif //PamVMCTrkF77.h
