#include "LEMuSRRNDMAGField.hh"
#include "G4ios.hh"
#include <iomanip.h>
#include "Randomize.hh"
#include "globals.hh"
#include "G4Transform3D.hh"
#include "G4UnitsTable.hh"


LEMuSRRNDMAGField::LEMuSRRNDMAGField(const G4ThreeVector FieldVector,   G4double rndness )
  :G4UniformMagField(FieldVector )
{
  BField=FieldVector;

  randomness=1;

  if(rndness<=1.&&rndness>=0)
    {
      randomness=rndness;
      G4cout <<"Mag field randomness = "<<randomness <<G4endl;
    }

}


LEMuSRRNDMAGField::~LEMuSRRNDMAGField()
{;}


void LEMuSRRNDMAGField::GetFieldValue (const G4double pos[4],
                                            G4double *field ) const 
{


  field[0]= 0.0;
  field[1]= 0.0;
  field[2]= 0.0;
  
  
  G4double costheta, sintheta, cosphi, sinphi, theta, phi;
  
  phi  = 2.0*M_PI*G4UniformRand()*rad;
  sinphi = sin(phi);
  cosphi = cos(phi);
  
  theta  = M_PI*G4UniformRand()*rad;
  sintheta = sin(theta);
  costheta = cos(theta);
  
  // rotation angles
  G4double px = sintheta*sinphi*sqrt(BField*BField);
  G4double py = sintheta*cosphi*sqrt(BField*BField);
  G4double pz = costheta*sqrt(BField*BField);
  
  G4ThreeVector direction0(px,py,pz);
  
  
  
  field[0]= BField.x()*(1-randomness) + direction0.x()*(randomness) ;//TAO
  field[1]= BField.y()*(1-randomness) + direction0.y()*(randomness) ;
  field[2]= BField.z()*(1-randomness) + direction0.z()*(randomness) ;
  
  
  
  //  G4cout<<"Field EM Field Value " << field[0]/gauss <<"gauss " <<field[1]/gauss <<"gauss "<< field[2]/gauss <<"gauss \n" <<G4endl;
  
  
}
