subroutine calculate_magnetic_field_p(pchunk,F,Y_R,Y_Z,B_R,B_PHI,B_Z)
INTEGER, INTENT(IN) :: pchunk
REAL(rp), DIMENSION(pchunk), INTENT(IN) :: Y_R,Y_Z
TYPE(FIELDS), INTENT(IN) :: F
REAL(rp), DIMENSION(pchunk), INTENT(OUT) :: B_R,B_PHI,B_Z
INTEGER :: pp
REAL(rp), DIMENSION(pchunk) :: PSIp
REAL(rp), DIMENSION(pchunk,2) :: A
REAL(rp) :: psip_conv
psip_conv=F%psip_conv
call EZspline_interp(bfield_2d%A, pchunk, Y_R, Y_Z, &
PSIp, ezerr)
call EZspline_error(ezerr)
! FR = (dA/dZ)/R
call EZspline_gradient(bfield_2d%A, pchunk, Y_R, Y_Z, &
A, ezerr)
call EZspline_error(ezerr)
!write(output_unit_write,'("dPSIp/dR: ",E17.10)') A(:,1)
!write(output_unit_write,'("dPSIp/dZ: ",E17.10)') A(:,2)
!write(output_unit_write,'("Y_R: ",E17.10)') Y_R
B_R = psip_conv*A(:,2)/Y_R
! FPHI = Fo*Ro/R
B_PHI = -F%Bo*F%Ro/Y_R
! FR = -(dA/dR)/R
! write(output_unit_write,'("R*B_Z: ",E17.10)') B_Z(1)
B_Z= -psip_conv*A(:,1)/Y_R
! write(output_unit_write,'("PSIp: ",E17.10)') PSIp
! write(output_unit_write,'("Y_R: ",E17.10)') Y_R(1)
! write(output_unit_write,'("Y_Z: ",E17.10)') Y_Z(1)
! write(output_unit_write,'("B_R: ",E17.10)') B_R
! write(output_unit_write,'("B_PHI: ",E17.10)') B_PHI
! write(output_unit_write,'("B_Z: ",E17.10)') B_Z
end subroutine calculate_magnetic_field_p