SUBROUTINE HQSCATT(KDLEN,KLEN,KDBDY,KMXBDY,KCMBDY,KOBSTYPE,KVNMRQ)

!**** *HQSCATT* - Choose scat wind nearest the High Resolution background

!     E. ANDERSSON            ECMWF          01/25/00

!     PURPOSE
!     -------

!     Choose scat wind nearest the High Resolution background

!**   INTERFACE
!     ---------
!     *CALL* *HQSCATT(KDLEN,KLEN,KDBDY,KCMBDY,KOBSTYPE,KVNMRQ)
!     WHERE KDLEN   = First dimension, observations
!           KLEN    = Actual number of observations
!           KDBDY   = Second dimension, data
!           KCMBDY  = Number of data in each report
!           KOBSTYPE= Observation type
!           KVNMRQ  = Variable number from NVNUMB table

!        HQSCATT is called from HOP/TL/AD

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

!**   MODIFICATIONS
!     -------------
!     Erik Andersson  25/01/00 : Original
!     ------------------------------------------------------------------

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

USE YOMCOCTP , ONLY : NSCATT
USE YOMDB
USE YOMVAR   , ONLY : NUPTRA

IMPLICIT NONE

INTEGER(KIND=JPIM),INTENT(IN)    :: KDLEN 
INTEGER(KIND=JPIM),INTENT(IN)    :: KDBDY 
INTEGER(KIND=JPIM),INTENT(IN)    :: KLEN 
INTEGER(KIND=JPIM),INTENT(IN)    :: KMXBDY 
INTEGER(KIND=JPIM),INTENT(IN)    :: KCMBDY(KDLEN) 
INTEGER(KIND=JPIM),INTENT(IN)    :: KOBSTYPE 
INTEGER(KIND=JPIM),INTENT(INOUT) :: KVNMRQ(KDLEN,KDBDY) 
INTEGER(KIND=JPIM), DIMENSION(KDLEN) :: ICLOSEST
REAL(KIND=JPRB), DIMENSION(KDLEN) :: ZDIST_CLOSEST
INTEGER(KIND=JPIM) :: JOBS,IBODY,JBDY
REAL(KIND=JPRB) :: ZDEPBU,ZDEPBV,ZDIST
REAL(KIND=JPRB) :: ZHOOK_HANDLE

#include "fcobs.h"

#include "openmp_obs.h"

!     ------------------------------------------------------------------
!*    1.       Departures from HR background are used to pick one pair of 
!              scat winds
!              ----------------------------------------------------------

IF (LHOOK) CALL DR_HOOK('HQSCATT',0,ZHOOK_HANDLE)
IF(KOBSTYPE /= NSCATT .AND. LHOOK) CALL DR_HOOK('HQSCATT',1,ZHOOK_HANDLE)
IF(KOBSTYPE /= NSCATT) RETURN

ZDIST_CLOSEST(:)=HUGE(ZDIST)
ICLOSEST(:)=0

DO JBDY=1,KMXBDY,2
  DO JOBS = 1,KLEN
    IF(JBDY > KCMBDY(JOBS)) CYCLE
    IF(KCMBDY(JOBS) < 4) CYCLE

    IBODY = MLNKH2B(JOBS)+JBDY-1
    ZDEPBU = ROBODY(IBODY  ,MDBIFC1(NUPTRA+1))
    ZDEPBV = ROBODY(IBODY+1,MDBIFC1(NUPTRA+1))
    ZDIST  = ZDEPBU**2 + ZDEPBV**2

    IF(ZDIST < ZDIST_CLOSEST(JOBS)) THEN
      ZDIST_CLOSEST(JOBS)=ZDIST
      ICLOSEST(JOBS)=JBDY
    ENDIF

  ENDDO
ENDDO

DO JBDY=1,KMXBDY,2
  DO JOBS = 1,KLEN
    IF(JBDY /= ICLOSEST(JOBS)) THEN
      KVNMRQ(JOBS,JBDY)=0
      KVNMRQ(JOBS,JBDY+1)=0
    ENDIF
  ENDDO
ENDDO

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