SUBROUTINE SEKF_MATINV(P_ZMAT,KINFO)

!**** *SEKF_MATINV*  - invert matrices

!     Input parameters.
!     -----------------

!     Purpose.
!     --------
!     (1) Invert matrices. This subroutine is copied from rokfcovar.F90

!**   Interface.
!     ----------
!        *CALL* *SEKF_MATINV(...)

!        Explicit arguments :      None
!        --------------------

!        Implicit arguments :      None
!        --------------------

!     Method.
!     -------
!        See documentation

!     Externals.
!     ----------

!     Reference.
!     ----------
!        ECMWF Research Department documentation of the IFS

!     Author.
!     -------
!        M. Drusch / M. Fisher  *ECMWF*

!     Modifications.
!     --------------

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

USE PARKIND1   , ONLY : JPIM, JPRB
USE YOMLUN     , ONLY : NULOUT
USE YOMHOOK    , ONLY : LHOOK, DR_HOOK

IMPLICIT NONE

REAL(KIND=JPRB)     ::  ZHOOK_HANDLE

REAL(KIND=JPRB),INTENT(INOUT) :: P_ZMAT(:,:)
INTEGER(KIND=JPIM) :: KINFO ! UNDETERMINED INTENT

INTEGER(KIND=JPIM) :: IDIM,ILWORK,INB
INTEGER(KIND=JPIM) :: ILAENV
EXTERNAL           :: ILAENV

INTEGER(KIND=JPIM), ALLOCATABLE :: IPIV(:)
REAL(KIND=JPRB), ALLOCATABLE :: ZWORK(:)

IF (LHOOK) CALL DR_HOOK('SEKF_MATINV',0,ZHOOK_HANDLE)

IDIM = SIZE(P_ZMAT,1)

INB = ILAENV(1, 'DGETRI', ' ', IDIM, -1, -1, -1)

ILWORK = IDIM * INB

ALLOCATE(IPIV(IDIM))
ALLOCATE(ZWORK(ILWORK))

WRITE(NULOUT,*) 'Call to DGETRF'
CALL FLUSH(NULOUT)
CALL DGETRF(IDIM, IDIM, P_ZMAT, IDIM, IPIV, KINFO)
WRITE(NULOUT,*) 'Exit from DGETRF'
CALL FLUSH(NULOUT)

IF (KINFO /= 0) THEN
    WRITE (NULOUT,*) 'SEKF_MATINV: DGETRF failed. INFO=',kinfo
    KINFO = 1
    CALL FLUSH(NULOUT)
!    CALL ABOR1 ('DGETRF failed')
    GOTO 666
ENDIF

WRITE(NULOUT,*) 'Call to DGETRI'
CALL FLUSH(NULOUT)
CALL DGETRI(IDIM, P_ZMAT, IDIM, IPIV, ZWORK, ILWORK, KINFO)
WRITE(NULOUT,*) 'Exit from DGETRI'
CALL FLUSH(NULOUT)

IF (KINFO /= 0) THEN
    WRITE (NULOUT,*) 'SEKF_MATINV: DGETRI failed. INFO=',kinfo
    KINFO = 2
    CALL FLUSH(NULOUT)
!    CALL ABOR1 ('DGETRI failed')
    GOTO 666
ENDIF

666 CONTINUE

IF (ALLOCATED(IPIV)) DEALLOCATE(IPIV)
IF (ALLOCATED(ZWORK)) DEALLOCATE(ZWORK)

IF (LHOOK) CALL DR_HOOK('SEKF_MATINV',1,ZHOOK_HANDLE)

END SUBROUTINE SEKF_MATINV
