module rfxqlo_xptr

  ! module for use by rfxqlo_helper library (only)
  !  acquire/release "old_xplasma" pointer "xptr"

  use plasma_state_mod
  use xplasma_obj_instance

  implicit NONE

  private
  save

  logical :: have_xptr = .FALSE.

  type :: interp_object
     type (xplasma), pointer :: s_xpobj => NULL()
  end type interp_object

  type (interp_object) :: xobj
  type (xplasma), pointer :: sps

  integer, parameter :: lunmsg = 6
  !------------------------------

  public :: rfxqlo_xptr_get
  public :: rfxqlo_xptr_release

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

contains

  subroutine rfxqlo_xptr_get(pstate,ierr)

    type(plasma_state) :: pstate
    integer, intent(out) :: ierr

    if(have_xptr) then
       write(lunmsg,*) ' ?rfxqlo_xptr_get: duplicate call, xptr already set.'
       ierr=1

    else
       xobj = transfer(pstate%iobj,xobj)
       sps => xobj%s_xpobj

       call grab_f77_xplasma(sps, ierr)
       if(ierr.ne.0) then
          write(lunmsg,*) ' ?rfxqlo_xptr_get: grab_f77_xplasma: ierr.ne.0'

       else
          have_xptr = .TRUE.
       endif
    endif

  end subroutine rfxqlo_xptr_get

  subroutine rfxqlo_xptr_release(ierr)

    integer, intent(out) :: ierr

    if(.not.have_xptr) then
       write(lunmsg,*) ' ?rfxqlo_xptr_release: no prior rfxqlo_xptr_get call.'
       ierr=1

    else
       call release_f77_xplasma(ierr)
       if(ierr.ne.0) then
          write(lunmsg,*) ' ?rfxqlo_xptr_get: release_f77_xplasma: ierr.ne.0'

       else
          have_xptr = .FALSE.
       endif
    endif

  end subroutine rfxqlo_xptr_release

end module rfxqlo_xptr
