subroutine nubeam_chk_state_grids(ss,ierr)

  ! nubeam component -- make sure output state object has necessary grids
  ! defined and allocated...
  !
  !  mods
  !    07jan2010    jim.conboy@ccfe.ac.uk
  !                 preset ierr = 0 
  !                 ( fixes undefined variable ref in nubeam_step ?? )
  !
  use nbi_com
  use plasma_state_mod

  implicit none

  !-----------------------------------
  ! passed:

  type (plasma_state)   :: ss

  integer, intent(out)  :: ierr    ! status code, 0=ok

  !-----------------------------------
  ! local:
  real(fp) :: ztol = 1.0e-6_fp
  real(fp) :: zmax
  !-----------------------------------

  ierr = 0
  if(ss%nrho_nbi.eq.0) then

     ss%nrho_nbi = nzp1
     call ps_alloc_plasma_state(ierr, state=ss)
     if(ierr.ne.0) then
        write(nonlin,*) ' ?? nubeam_chk_state_grids: failed to allocate rho_nbi grid in state.'
        return
     endif

     ss%rho_nbi = xi(lcentr:lep1,1)

  else if(ss%nrho_nbi.ne.nzp1) then

     ierr=99
     write(nonlin,*) ' ?? nubeam_chk_state_grids: gridsize inconsistency:'
     write(nonlin,*) '    in nbi_com the gridsize (nzp1) is: ',nzp1
     write(nonlin,*) '    in the state, ss%nrho_nbi is: ',ss%nrho_nbi
     return

  else

     zmax = maxval( abs( xi(lcentr:lep1,1) - ss%rho_nbi(1:nzp1) ))
     if(zmax.gt.ztol) then

        ierr=100
        write(nonlin,*) ' ?? nubeam_chk_state_grids: grid inconsistency:'
        write(nonlin,*) '    in nbi_com: xi(lcentr:lep1,1): ',xi(lcentr:lep1,1)
        write(nonlin,*) '    in state: ss%rho_nbi: ',ss%rho_nbi
        return
     endif
  endif

  if(ss%nrho_fus.eq.0) then

     ss%nrho_fus = nzp1
     call ps_alloc_plasma_state(ierr, state=ss)
     if(ierr.ne.0) then
        write(nonlin,*) ' ?? nubeam_chk_state_grids: failed to allocate rho_fus grid in state.'
        return
     endif

     ss%rho_fus = xi(lcentr:lep1,1)

  else if(ss%nrho_fus.ne.nzp1) then

     ierr=99
     write(nonlin,*) ' ?? nubeam_chk_state_grids: gridsize inconsistency:'
     write(nonlin,*) '    in fus_com the gridsize (nzp1) is: ',nzp1
     write(nonlin,*) '    in the state, ss%nrho_fus is: ',ss%nrho_fus
     return

  else

     zmax = maxval( abs( xi(lcentr:lep1,1) - ss%rho_fus(1:nzp1) ))
     if(zmax.gt.ztol) then

        ierr=100
        write(nonlin,*) ' ?? nubeam_chk_state_grids: grid inconsistency:'
        write(nonlin,*) '    in fus_com: xi(lcentr:lep1,1): ',xi(lcentr:lep1,1)
        write(nonlin,*) '    in state: ss%rho_fus: ',ss%rho_fus
        return
     endif
  endif

end subroutine nubeam_chk_state_grids
