SUBROUTINE ONEDVAR_RAINTB_PRC(KCNTA)

!****-------------------------------------------------------------------
!**** *ONEDVAR_RAINTB_PRC* - ONEDVAR LOAD BALANCING
!****-------------------------------------------------------------------
!     Purpose.   Set up helper processors
!     --------

!**   Interface.
!     ----------

!        Explicit arguments :  KCNTA
!        --------------------

!     Method.
!     -------

!     Externals.
!     ----------
!       Called from GP_MODEL

!     Author.
!     -------
!        John Hague   *ECMWF* 22-Nov-2005

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

USE PARKIND1  , ONLY : JPIM     ,JPRB
USE YOMHOOK  , ONLY : LHOOK    ,DR_HOOK
USE YOMCT0    , ONLY : NPROC
USE YOMMP     , ONLY : MYPROC
USE YOMRAIN_LB, ONLY : ICOPROCS, CLPROC, JPHLP

IMPLICIT NONE

INTEGER(KIND=JPIM), INTENT(IN) :: KCNTA(NPROC)

REAL(KIND=JPRB)    :: ZTMP, ZAVG
INTEGER(KIND=JPIM) :: ICNTB(NPROC),INDXA(NPROC)
INTEGER(KIND=JPIM) :: J, IM, IH, IDONE

INTEGER(KIND=JPIM) :: IFIRST=0

REAL(KIND=JPRB) :: ZHOOK_HANDLE

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

IFIRST=IFIRST+1
ICNTB=KCNTA
CALL ISORTX(ICNTB,1,NPROC,INDXA)
IM=NPROC
IH=1
IDONE=0
ICOPROCS(:)=0
ZAVG=SUM(ICNTB)/NPROC
CLPROC=" "
DO WHILE (IDONE == 0)
  ZTMP=ICNTB(IM)
  DO J=1,JPHLP
    IF(IH < IM ) THEN
      ZTMP=ZTMP-ICNTB(IH)
      IF(ZTMP > J*ZAVG) THEN
        IF(INDXA(IM) == MYPROC) THEN
          CLPROC="M"
          ICOPROCS(1) = ICOPROCS(1)+1
          ICOPROCS(1+J) = INDXA(IH)
        ENDIF
        IF(INDXA(IH) == MYPROC) THEN
          CLPROC="H"
          ICOPROCS(1) = INDXA(IM)
        ENDIF
        IH=IH+1
      ENDIF
    ENDIF
  ENDDO
  IM=IM-1
  IF(IM <= IH ) IDONE=1
ENDDO

IF(CLPROC == "M")THEN
! WRITE(0,'(I3,A,I4,A,16I4)') IFIRST, &
!  & " RAIN ASSIM LOAD BAL: ME=MASTER =",MYPROC, &
!  & "  HELPERS =",(ICOPROCS(J),J=2,ICOPROCS(1)+1)
  WRITE(0,'(I3,A,I4,A,I4)') IFIRST, &
  & " RAIN ASSIM LOAD BAL: ME=MASTER =",MYPROC, &
  & "  HELPERS(COUNT) =",ICOPROCS(1)
ENDIF
!IF(CLPROC == "H") WRITE(0,'(I3,A,I4,A,I4)') IFIRST, &
!  & " RAIN ASSIM LOAD BAL: ME=HELPER =",MYPROC,"  MASTER =",ICOPROCS(1)

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

END SUBROUTINE ONEDVAR_RAINTB_PRC
