subroutine nbi_inputs(filename,action,ierr)

  ! read or write (non-xplasma) input data for nubeam calculation.
  !
  ! note modification: workpath value is written.  if the code using this
  ! routine wants a different workpath than the one recorded, it can use
  !    call nubeam_workpat_reset(' ') 
  ! ...e.g. to select current working directory.
  ! 
  ! the following code sequence is expected:
  !   serial client: write xplasma state, write inputs (nbi_inputs)
  !   pll server:    read xplasma state (eq_save), read inputs (nbi_inputs)
  !   pll server:    calculate nubeam step (nubeam_driver)
  !   pll server:    write xplasma state (eq_restore), write outputs
  !   serial client: read xplasma state, read outputs
  ! see nbo_outputs.f90 -- write/read scalar outputs not in xplasma.

  use nbi_com
  use ezcdf

  implicit none

  character*(*), intent(in) :: filename   ! state filename
  character*1, intent(in) :: action   ! "W" or "w": write, "R" or "r": restore

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

  !---------------------------------------------------

  integer :: icdf                     ! netcdf channel id
  integer :: iwarn

  character*1 actup
  logical :: ksave1
  !---------------------------------------------------

  actup=action
  call uupper(actup)

  ierr=0

  if(actup.eq.'W') then
     
     ! write... suppress only_io & ref_namelist switches

     ksave1 = only_io
     only_io = .false.  ! subprocess will do the real calculation

     !!!!  zsave1 = workpath
     !!!!  workpath = ' '     ! it will operate where the files are

     call ezcdf_open(icdf,filename,'W',ierr)
     if(ierr.ne.0) then
        write(nonlin,*) ' ?nbi_inputs(...,"W",...) ezcdf_open: ierr= ',ierr
     else

        call nbi_inputs_write(icdf)
        call ezcdf_close(icdf)

     endif

     only_io = ksave1
     !!!!  workpath = zsave1

  else if(actup.eq.'R') then

     ! read...

     call ezcdf_open(icdf,filename,'R',ierr)
     if(ierr.ne.0) then
        write(nonlin,*) ' ?nbi_inputs(...,"R",...) ezcdf_open: ierr= ',ierr
     else

        call nbi_inputs_read(icdf,ierr)
        call ezcdf_close(icdf)

        if(ierr.ne.0) then
           write(nonlin,*) ' ?nbi_inputs(...,"R",...): netcdf file read error.'
           write(nonlin,*) '  file may be from a different version of nubeam.'
        endif

     endif

  endif

  return
end subroutine nbi_inputs
