subroutine rfxqlo_free(iwarn)
  use rfxqlo_private
  implicit NONE

  integer, intent(out) :: iwarn  ! =0: normal; =1: no prior allocation.

  !  free up memory in module rfxqlo_private

  if(init) then
     iwarn = 0   ! memory was freed

     !---------------- 
     n_antenna = 0
     max_nphi = 0

     if(allocated(calculated)) deallocate(calculated)
     if(allocated(outpros)) deallocate(outpros)

     if(allocated(x_qlo)) deallocate(x_qlo,xb_qlo,dv_qlo,v_qlo)
     if(allocated(qzb)) deallocate(qzb,qzc,gzb,gzc)
     nx_qlo = 0

     call rfxqlo_misc_free

     !---------------- 
     vacden = 0
     vactemp = 0
     placur = 0
     tflux = 0
     rmaj0 = 0
     btor0 = 0

     nvvmoms = 0

     if(allocated(vvrmoms)) deallocate(vvrmoms,vvzmoms)

     !---------------- 
     selected_antenna = 0
     selected_nphi = 0

     if(allocated(antenna_array)) deallocate(antenna_array)

     call rfxqlo_wavefields_free

     !---------------- 
     init=.FALSE.
     ready=.FALSE.

     !---------------- 
     !  Bessel table...

     argmax_save = 0
     if(allocated(besa)) deallocate(arga,besa)

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

  else
     iwarn = 1   ! memory not freed (module was already deallocated).

  endif

end subroutine rfxqlo_free

subroutine rfxqlo_misc_free

  ! deallocate QLO field/metric stuff originally from FPPMOD

  use rfxqlo_private
  implicit NONE

  if(allocated(BAVGOFR)) then
     deallocate(BAVGOFR,BDELOFR,BMAXOFR,BMINOFR,DELTHOFB,NUMTHOFB)
     deallocate(OMPPOFR,YOFBR,THOFBR)
     deallocate(PSI)
     deallocate(RATBMAXM,RATBMAXP,RATBMIN)
     deallocate(YATBMAXM,YATBMAXP,YATBMIN)
     deallocate(THBMAXM,THBMAXP,THBMIN)
  endif

end subroutine rfxqlo_misc_free
