subroutine nbi_put_fbm(id_mcgrid,zname,zlabel,id_vpv,zconve,efbmb,zconv,fbm, &
     inume,inuma,idime,idima,idimz,jerr)

  use iso_c_binding, only: fp => c_double
  use xplasma_obj_instance

  ! transfer distribution function to xplasma
  ! also create the energy grid if necessary

  integer, intent(in) :: id_mcgrid    ! irreg. spatial grid id
  character*(*), intent(in) :: zname
  character*(*), intent(in) :: zlabel

  integer, intent(in) :: id_vpv       ! pitch (vpll/v) grid id

  integer, intent(in) :: inume        ! # of energy zones
  integer, intent(in) :: inuma        ! # of pitch zones
  integer, intent(in) :: idime,idima,idimz  ! fbm array dimensions

  real(fp), intent(in) :: zconve        ! energy grid units conversion
  real(fp) :: efbmb(inume+1)            ! energy grid
  real(fp), intent(in) :: zconv         ! fbm units conversion
  real(fp) :: fbm(idime,idima,idimz)    ! fbm -- distribution function

  integer, intent(out) :: jerr        ! error code returned

  !-----------------------
  character*32 zname_ecoord,zname_egrid
  integer :: id_ecoord,id_egrid,id_pro
  logical, parameter :: not_periodic = .false.
  real(fp), dimension(:,:,:), allocatable :: fbm_tmp
  !-----------------------

  zname_egrid='e'//trim(zname)
  zname_ecoord=trim(zname_egrid)//'_coord'

  call xplasma_gridid(s,zname_egrid,id_egrid)
  if(id_egrid.eq.0) then

     call xplasma_create_coord(s,zname_ecoord,not_periodic,id_ecoord,jerr, &
          label='fast ion energy',units='kev')

     if(jerr.ne.0) return

     call xplasma_create_grid(s,zname_egrid,id_ecoord,zconve*efbmb, &
          id_egrid,jerr, &
          label='fast ion energy')

     if(jerr.ne.0) return

  endif

  allocate(fbm_tmp(inume,inuma,idimz))
  fbm_tmp = zconv*fbm(1:inume,1:inuma,1:idimz)

  call xplasma_mcgrid_putobj(s,id_mcgrid,zname,id_pro,jerr, &
       data_3d = fbm_tmp, &
       gridid1=id_egrid, gridid2=id_vpv, normcode=2, &
       label=zlabel,units='#/de/da/m^3')

  deallocate(fbm_tmp)

end subroutine nbi_put_fbm
