SUBROUTINE MINIMA(PDIS,KDIR,KDIRSUR2,KNBMIN,KMIN,PRES1)
!*******************************************************************************
!     LOOKS FOR MINIMA IN THE TABLE PDIS(KDIR)
!     BY COMPARING VALUES TWO AT A TIME
!     POINTS FOR WHICH D>RSCAMDI ARE DISCARDED
!     INPUT : PDIS    TABLE OF DISTANCES D
!     OUTPUT: KNBMIN  NUMBER OF MINIMA FOUND
!             KMIN    TABLE CONTAINING THE INDICES OF
!                     MINIMA
!*******************************************************************************

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

USE PARERSCA , ONLY : JPDIRMAX
USE YOMERSCA , ONLY : RSCAMDI

IMPLICIT NONE

INTEGER(KIND=JPIM)                    ,INTENT(IN)    :: KDIR 
INTEGER(KIND=JPIM)                    ,INTENT(IN)    :: KDIRSUR2 
INTEGER(KIND=JPIM)                    ,INTENT(INOUT) :: KNBMIN 
REAL(KIND=JPRB)   ,DIMENSION(KDIR)    ,INTENT(IN)    :: PDIS 
INTEGER(KIND=JPIM),DIMENSION(KDIRSUR2),INTENT(OUT)   :: KMIN 
REAL(KIND=JPRB)                       ,INTENT(IN)    :: PRES1 

INTEGER(KIND=JPIM) :: I, ILOW, IMAXI, INDX, J, JNB

REAL(KIND=JPRB), DIMENSION(JPDIRMAX) :: ZDISM
REAL(KIND=JPRB) :: ZRESLIM
REAL(KIND=JPRB) :: ZHOOK_HANDLE

#include "abor1.intfb.h"

IF (LHOOK) CALL DR_HOOK('MINIMA',0,ZHOOK_HANDLE)
ILOW = 0
ZRESLIM = 2.0_JPRB*PRES1
DO J = 1, KDIR
  IF( PDIS(J) < ZRESLIM ) ILOW = ILOW + 1
ENDDO
ILOW = MIN(ILOW,KDIR)
ILOW = ILOW/4

DO J = 1, KDIR
  ZDISM(J) = 0.0_JPRB
  DO JNB = -ILOW, ILOW
    INDX = MOD( J+JNB-1 + KDIR, KDIR ) + 1
    ZDISM(J) = ZDISM(J) + PDIS(INDX)
  ENDDO
ENDDO

IMAXI=KNBMIN
KNBMIN=0
I=2
10 CONTINUE
IF(I > IMAXI-1)GOTO 20
IF(PDIS(I+1) == RSCAMDI)THEN
  I=I+3
  GOTO 10
ELSEIF(PDIS(I) == RSCAMDI)THEN
  I=I+2
  GOTO 10
ELSEIF(PDIS(I-1) == RSCAMDI)THEN
  I=I+1
  GOTO 10
ELSE
  IF(ZDISM(I) < ZDISM(I-1).AND.ZDISM(I) <= ZDISM(I+1))THEN
    KNBMIN=KNBMIN+1
    KMIN(KNBMIN)=I
  ENDIF
  I=I+1
ENDIF
GOTO 10

!  PDIS(IMAXI) MINIMUM ?

20 CONTINUE
IF(PDIS(IMAXI) /= RSCAMDI)THEN
  IF(ZDISM(1) >= ZDISM(IMAXI))THEN
    IF(ZDISM(IMAXI-1) > ZDISM(IMAXI))THEN
      KNBMIN=KNBMIN+1
      KMIN(KNBMIN)=IMAXI
    ENDIF
  ENDIF
ENDIF

!  PDIS(1)  MINIMUM ?

IF(PDIS(1) /= RSCAMDI)THEN
  IF(ZDISM(IMAXI) > ZDISM(1))THEN
    IF(ZDISM(2) >= ZDISM(1))THEN
      KNBMIN=KNBMIN+1
      KMIN(KNBMIN)=1
    ENDIF
  ENDIF
ENDIF
IF(KNBMIN >= KDIRSUR2)THEN
  CALL ABOR1('KNBMIN >= KDIRSUR2')
ENDIF
IF (LHOOK) CALL DR_HOOK('MINIMA',1,ZHOOK_HANDLE)
END SUBROUTINE MINIMA
