SUBROUTINE THIBOX(PLAT,PLON,PBSIZE,KBOX,LDMASK)

!**** SUBROUTINE THIBOX - BOX INDEX FOR SATELLITE DATA THINNING

!          HEIKKI JARVINEN   ECMWF          15/AUG/1995

!*    PURPOSE
!     -------

!        THINNIG THE SATELLITE DATA REQUIRES A GEOGRAPHICALLY FIXED
!     NET OF BOXES. INDEX OF SUCH A BOX IS CALCULATED HERE.

!**   INTERFACE
!     ---------

!     ***CALL THIBOX(PLAT,PLON,PBSIZE,KBOX,LDMASK)
!     WHERE PLAT   = LATITUDE OF OBSERVATION IN RADIANS
!           PLON   = LONGITUDE OF OBSERVATION IN RADIANS
!           PBSIZE = BOX SIZE IN DEGREES
!           KBOX   = BOX INDEX
!           LDMASK = MASK

!        THIBOX IS CALLED BY SUBROUTINE THINN

!*    METHOD
!     ------

!*    EXTERNALS
!     ---------

!**   MODIFICATIONS
!     -------------
!     Erik Andersson, Mats Hamrud 06/10/97  - Baah.
!     Sami Saarinen               25/02/05  - Yeeh.

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

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

USE YOMANCS  , ONLY : RADIANS  ,RDEGREES

IMPLICIT NONE

REAL(KIND=JPRB)   ,INTENT(IN)    :: PLAT(:) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PLON(:) 
REAL(KIND=JPRB)   ,INTENT(IN)    :: PBSIZE 
INTEGER(KIND=JPIM),INTENT(OUT)   :: KBOX(:) 
LOGICAL           ,INTENT(IN)    :: LDMASK(:) 
INTEGER(KIND=JPIM) :: ISCALE, IXC, IYC, J
INTEGER(KIND=JPIM)               :: ILEN
REAL(KIND=JPRB) :: ZLAT, ZLON
REAL(KIND=JPRB) :: ZHOOK_HANDLE

#include "abor1.intfb.h"

!*
!     ------------------------------------------------------------------

!        1.       THINNING BOX INDEX
!                 ------------------

IF (LHOOK) CALL DR_HOOK('THIBOX',0,ZHOOK_HANDLE)
ISCALE=1000
!IF(PBSIZE < 100._JPRB/ISCALE) CALL ABOR1('THIBOX: PBSIZE OR ISCALE TOO SMALL') ! ALADIN
IF(PBSIZE < 50._JPRB/ISCALE) CALL ABOR1('THIBOX: PBSIZE OR ISCALE TOO SMALL')   ! AROME

ILEN = SIZE(PLAT)
DO J=1,ILEN
  IF(.NOT.LDMASK(J)) CYCLE

  ZLAT = PLAT(J)*RDEGREES
  ZLON = PLON(J)*RDEGREES
  IF(ZLON > 180._JPRB) ZLON = ZLON - 360._JPRB

  IYC  = NINT(ZLAT/PBSIZE)
  IXC  = MAX(NINT(360._JPRB*COS(IYC*PBSIZE*RADIANS)/PBSIZE),1)
  KBOX(J) = (IYC+ISCALE/2)*ISCALE + NINT(ZLON*IXC/360._JPRB) + ISCALE/2
ENDDO

IF (LHOOK) CALL DR_HOOK('THIBOX',1,ZHOOK_HANDLE)
END SUBROUTINE THIBOX
