subroutine rf_wavecode_driver(npserve,zcp_serve,ierr)

  use logmod
  use rfxqlo_interface
  implicit NONE

  integer, intent(in) :: npserve   ! .gt.0 to indicated wavecode server
  real*8, intent(out) :: zcp_serve ! server CPU time 

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

  !  write files (for debugging or server invocation) and run wavecode
  !---------------------------------------------------------------------

  type (rfxqlo_system) :: zsys
  integer :: lunmsg = 6

  !---------------------------------------------------------------------
  external :: rf_wavecode_call
  !---------------------------------------------------------------------

  call enterLog("rf_wavecode_driver")  ! all returns through exitLog()

  call rfxqlo_system_get(zsys,ierr)
  if(ierr.ne.0) then
     write(lunmsg,*) ' ?rf_wavecode_driver: rfxqlo_system_get failure.'
     goto 900
  endif
  
  !  write xplasma  -- has input profiles (plasma parameters) for wave code

  call eq_save(trim(zsys%filepath)//trim(zsys%run_id)//'_rfcode.cdf',ierr)
  if(ierr.ne.0) then
     write(lunmsg,*) ' ?rf_wavecode_driver: eq_save error on file: '// &
          trim(zsys%filepath)//trim(zsys%run_id)//'_rfcode.cdf'
     goto 900
  endif

  !  write rfxqlo file -- for debugging or for remote execution of wavecode...

  call rfxqlo_inputfile_create( &
       trim(zsys%filepath)//trim(zsys%run_id)//'_rfxqlo_in.cdf',ierr)
  if(ierr.ne.0) then
     write(lunmsg,*) &
          ' ?rf_wavecode_driver: rfxqlo_inputfile_create error on file: '// &
          trim(zsys%filepath)//trim(zsys%run_id)//'_rfxqlo_in.cdf'
     goto 900
  endif

  !--------------------------------
  !  call the wavecode in a loop over all frequencies and Nphi values

  call rf_wavecode_exec(rf_wavecode_call,npserve,zcp_serve,ierr)

  if(ierr.ne.0) then
     write(lunmsg,*) ' ?rf_wavecode_driver: rf_wavecode_exec failure!'
     goto 900
  endif

  !  write the wavecode output to NetCDF (for debugging)

  call rfxqlo_outputfile_create( &
       trim(zsys%filepath)//trim(zsys%run_id)//'_rfxqlo_out.cdf',ierr)
  if(ierr.ne.0) then
     write(lunmsg,*) &
           ' ?rf_wavecode_driver: rfxqlo_outputfile_create error on file: '// &
           trim(zsys%filepath)//trim(zsys%run_id)//'_rfxqlo_out.cdf'
     goto 900
  endif

900 continue
  call exitLog("rf_wavecode_driver")  
end subroutine rf_wavecode_driver
