! (C) Copyright 2005- ECMWF.
! (C) Copyright 2013- Meteo-France.
! 
! This software is licensed under the terms of the Apache Licence Version 2.0
! which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
! In applying this licence, ECMWF does not waive the privileges and immunities
! granted to it by virtue of its status as an intergovernmental organisation
! nor does it submit to any jurisdiction.
!

MODULE MPL_TESTSOME_MOD

USE MPL_MPIF
USE EC_PARKIND, ONLY : JPIM
USE MPL_MESSAGE_MOD
IMPLICIT NONE

! P. Marguinaud : 01-Jan-2011 

! KARRAY_OF_REQUESTS  (see MPI_TESTSOME)
! KARRAY_OF_INDICES   (see MPI_TESTSOME)
! KARRAY_OF_INDICES1  pending requests
! KOUTCOUNT1          number of pending requests

PRIVATE
PUBLIC :: MPL_TESTSOME

CONTAINS

SUBROUTINE MPL_TESTSOME (KARRAY_OF_REQUESTS, KARRAY_OF_INDICES,      &
                       & KARRAY_OF_INDICES1, KOUTCOUNT, KOUTCOUNT1,  &
                       & KERROR, CDSTRING, LDWAIT)
INTEGER(KIND=JPIM), INTENT (IN)  :: KARRAY_OF_REQUESTS (:)
INTEGER(KIND=JPIM), INTENT (OUT) :: KARRAY_OF_INDICES (:)
INTEGER(KIND=JPIM), INTENT (OUT), OPTIONAL :: KARRAY_OF_INDICES1 (:)
INTEGER(KIND=JPIM), INTENT (OUT), OPTIONAL :: KOUTCOUNT
INTEGER(KIND=JPIM), INTENT (OUT), OPTIONAL :: KOUTCOUNT1
INTEGER(KIND=JPIM), INTENT (OUT), OPTIONAL :: KERROR
CHARACTER(LEN=*),   INTENT(IN),   OPTIONAL :: CDSTRING
LOGICAL,            INTENT(IN),   OPTIONAL :: LDWAIT

INTEGER(KIND=JPIM) :: IERROR
INTEGER(KIND=JPIM) :: IINCOUNT
INTEGER(KIND=JPIM) :: IOUTCOUNT
INTEGER(KIND=JPIM) :: IARRAY_OF_STATUSES (MPI_STATUS_SIZE, SIZE (KARRAY_OF_REQUESTS))
INTEGER(KIND=JPIM) :: II, IJ, IK
LOGICAL :: LLWAIT
LOGICAL :: LLABORT=.TRUE.



IINCOUNT = SIZE (KARRAY_OF_REQUESTS)
KARRAY_OF_INDICES = -1

LLWAIT = .FALSE.
IF (PRESENT (LDWAIT)) LLWAIT = LDWAIT

IF (LLWAIT) THEN
  CALL MPI_WAITSOME(IINCOUNT, KARRAY_OF_REQUESTS, IOUTCOUNT, &
                    KARRAY_OF_INDICES, IARRAY_OF_STATUSES, IERROR)
ELSE
  CALL MPI_TESTSOME(IINCOUNT, KARRAY_OF_REQUESTS, IOUTCOUNT, &
                    KARRAY_OF_INDICES, IARRAY_OF_STATUSES, IERROR)
ENDIF

IF (PRESENT (KOUTCOUNT)) THEN
  KOUTCOUNT = IOUTCOUNT
ENDIF

IF (PRESENT (KOUTCOUNT1)) THEN
  KOUTCOUNT1 = IINCOUNT - IOUTCOUNT
ENDIF

IF (PRESENT (KARRAY_OF_INDICES1)) THEN
  KARRAY_OF_INDICES1 = -1
  IJ = 1
  IK = 1
  DO II = 1, IINCOUNT
    IF (II .EQ. KARRAY_OF_INDICES (IJ)) THEN
      IJ = IJ + 1
    ELSE
      KARRAY_OF_INDICES1 (IK) = II
      IK = IK + 1
    ENDIF
  ENDDO
ENDIF

IF (PRESENT (KERROR)) THEN
  KERROR = IERROR
ELSE
  IF(IERROR /= 0) CALL MPL_MESSAGE(IERROR,'MPL_TESTSOME',CDSTRING,LDABORT=LLABORT)
ENDIF

END SUBROUTINE MPL_TESTSOME

END MODULE MPL_TESTSOME_MOD
