SUBROUTINE SUJBGPTOMAT (KSCALE,KNUMB,YD_PVC,PLON,PLAT,KGPTOMAT)

!      SUJBGPTOMAT Determine which matrix is updated by each gridpoint
!                  in the wavelet Jb statistics calculation

!     Arguments :
!     -----------
!     Input:
!       KSCALE - Wavelet scale
!       KNUMB - number of elements for which computations are performed
!       YD_PVC - structure containing the matrices
!       PLON   - longitudes of gridpoints
!       PLAT   - latitudes of gridpoints
!       KGPTOMAT - Output array of matrix indices for each gridpoint

!     Author:  M. Fisher  *ECMWF* (based on JBVCORG)
!     -------

!     Modifications:
!     --------------
!     ORIGINAL   2004-01-08.
!     ------------------------------------------------------------------

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

USE YOMDIM   , ONLY : NPROMA
USE YOMCST   , ONLY : RPI
USE YOMWAVELET,ONLY : WAVELET_VCOR_STRUCT

IMPLICIT NONE

INTEGER(KIND=JPIM),INTENT(IN)    :: KSCALE 
INTEGER(KIND=JPIM),INTENT(IN)    :: KNUMB
TYPE (WAVELET_VCOR_STRUCT), INTENT(IN) :: YD_PVC
REAL(KIND=JPRB)   ,INTENT(IN)    :: PLON(NPROMA)
REAL(KIND=JPRB)   ,INTENT(IN)    :: PLAT(NPROMA)
INTEGER(KIND=JPIM),INTENT(OUT)   :: KGPTOMAT(KNUMB)

INTEGER(KIND=JPIM) :: ILM, JGP, ILATN, JLAT, JLON
REAL(KIND=JPRB)    :: ZLONGP, ZLATGP
REAL(KIND=JPRB) :: ZHOOK_HANDLE

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

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

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


!     Loop over gridpoints

DO JGP=1,KNUMB
  ZLONGP=PLON(JGP)
  ZLATGP=PLAT(JGP)

!         Find which matrix is updated by the gridpoint

  ILATN = 1
  DO JLAT=1,YD_PVC%NLATS-1
    IF (ZLATGP > 0.5_JPRB*( YD_PVC%LATSG(JLAT+YD_PVC%NLAT_OFFSET  ) &
     & +YD_PVC%LATSG(JLAT+YD_PVC%NLAT_OFFSET+1))) EXIT  
    ILATN=ILATN+1
  ENDDO

  ILM=SUM(YD_PVC%NLONS(1:ILATN-1))+1
  DO JLON=1,YD_PVC%NLONS(ILATN)-1
    IF (ABS( YD_PVC%LON0G(ILATN+YD_PVC%NLAT_OFFSET) &
     & +REAL(JLON-1+YD_PVC%NLON_OFFSET(ILATN),JPRB)*YD_PVC%DLON(ILATN) &
     & -ZLONGP) <=0.5_JPRB*YD_PVC%DLON(ILATN)  .OR.  &
     & ABS( YD_PVC%LON0G(ILATN+YD_PVC%NLAT_OFFSET) &
     & +REAL(JLON-1+YD_PVC%NLON_OFFSET(ILATN),JPRB)*YD_PVC%DLON(ILATN) &
     & -ZLONGP) >=2.0_JPRB*RPI-0.5*YD_PVC%DLON(ILATN) ) EXIT  
    ILM=ILM+1
  ENDDO

  KGPTOMAT(JGP) = ILM
ENDDO

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

END SUBROUTINE SUJBGPTOMAT
