MODULE EFTINV_MOD
CONTAINS
SUBROUTINE EFTINV(ALLOCATOR,HFTINV,PREEL,PREEL_REAL,KF_FS)

USE PARKIND1  ,ONLY : JPIM, JPRB, JPIB
USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK, JPHOOK

USE TPM_GEN, ONLY : NCUR_RESOL
USE TPM_DISTR       ,ONLY : D
USE TPM_DIM         ,ONLY : R
USE TPMALD_DIM      ,ONLY : RALD

USE TPM_HICFFT      ,ONLY : EXECUTE_INV_FFT

USE FTINV_MOD, ONLY : FTINV_HANDLE
USE ABORT_TRANS_MOD ,ONLY : ABORT_TRANS

USE ISO_C_BINDING
USE BUFFERED_ALLOCATOR_MOD

!

IMPLICIT NONE

TYPE(BUFFERED_ALLOCATOR), INTENT(IN) :: ALLOCATOR
TYPE(FTINV_HANDLE), INTENT(IN) :: HFTINV
REAL(KIND=JPRB), POINTER,   INTENT(INOUT)  :: PREEL(:)   ! (IRLEN+2)*KF_FS*NDGL_FS
REAL(KIND=JPRB), POINTER,   INTENT(OUT)  :: PREEL_REAL(:)   ! (IRLEN+2)*KF_FS*NDGL_FS
INTEGER(KIND=JPIM), INTENT(IN)  :: KF_FS

INTEGER(KIND=JPIM) :: JLOT, IRLEN
REAL(KIND=JPHOOK) :: ZHOOK_HANDLE

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

!*       1.       PERFORM LEGENDRE TRANFORM.
!                 --------------------------

IF (LHOOK) CALL DR_HOOK('EFTINV_MOD:EFTINV',0,ZHOOK_HANDLE)

IRLEN=R%NDLON+R%NNOEXTZG

#ifdef IN_PLACE_FFT
    PREEL_REAL => PREEL
#else
    CALL ASSIGN_PTR(PREEL_REAL, GET_ALLOCATION(ALLOCATOR, HFTINV%HREEL_REAL),&
      & 1_JPIB, 1_JPIB*KF_FS*D%NLENGTF*C_SIZEOF(PREEL_REAL(1)))
#endif

JLOT=SIZE(PREEL)/(IRLEN+2)

IF (JLOT==0) THEN
  IF (LHOOK) CALL DR_HOOK('EFTINV_MOD:EFTINV',1,ZHOOK_HANDLE)
  RETURN
ENDIF

!$ACC DATA PRESENT(PREEL,RALD%NLOENS_LON,RALD%NOFFSETS_LON)
CALL EXECUTE_INV_FFT(PREEL,PREEL_REAL,NCUR_RESOL,JLOT, &
    & LOENS=RALD%NLOENS_LON, &
    & OFFSETS=RALD%NOFFSETS_LON,ALLOC=ALLOCATOR%PTR)
!$ACC END DATA

IF (LHOOK) CALL DR_HOOK('EFTINV_MOD:EFTINV',1,ZHOOK_HANDLE)

END SUBROUTINE EFTINV
END MODULE EFTINV_MOD