FUNCTION MWIMAGER_CLOUD( K1D_Y, PTB_OBS, KSENS_ID, PLWP, LD_D37, LD_LWP, LD_MWAVE)

! This function is used by both rad1cemis.F90 and onedvar_fstscrn.F90
! to perform a cloud and rain test and to decide whether to pass data 
! through the clear or the rainy sky paths.

! Function returns TRUE if the observation appears cloudy or rainy and
! FALSE if the observation appears clear.

! Changes
! -------

! 15-Sept-2007  Alan Geer      Initial version
! 17-Sept-2008  Alan Geer      Use different coefficients with all-sky 4D-Var
!  9-Jan -2009  Alan Geer      Remove optional ld_mwave (does not work due to 
!                              lack of explicit F90 function interface).

USE PARKIND1   , ONLY: JPIM, JPRB
USE YOMHOOK    , ONLY: LHOOK, DR_HOOK
USE YOMANCS    , ONLY: RMDI 
USE MWIMAGER_MIX, ONLY: YCOEFF, RDTB_LIMIT, GET_LWPCOEFF 

IMPLICIT NONE

REAL(KIND=JPRB), EXTERNAL :: MWIMAGER_LWP

INTEGER(KIND=JPIM), INTENT(IN) :: KSENS_ID ! I: The sensor ID number.  Eg, SSM/I=6, TMI=17.
INTEGER(KIND=JPIM), INTENT(IN) :: K1D_Y    ! I: Number of channels
REAL(KIND=JPRB), INTENT(IN)    :: PTB_OBS(K1D_Y) ! I: TB obs for a single profile. [K]
REAL(KIND=JPRB), INTENT(OUT)   :: PLWP     ! O: Liquid water path [kg m^-2]
LOGICAL, INTENT(OUT)           :: LD_D37   ! O: Polarisation difference test triggered
LOGICAL, INTENT(OUT)           :: LD_LWP   ! O: LWP test triggered
LOGICAL, INTENT(IN)            :: LD_MWAVE ! I: Different set of coefficients for mwave
LOGICAL                        :: MWIMAGER_CLOUD ! O: Clear = FALSE

TYPE(YCOEFF)    :: YLCOEFF
REAL(KIND=JPRB) :: ZHOOK_HANDLE

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

MWIMAGER_CLOUD = .FALSE.
LD_D37 = .FALSE.
LD_LWP = .FALSE.


IF ( GET_LWPCOEFF(KSENS_ID, YLCOEFF, LD_MWAVE) ) THEN

  PLWP = MWIMAGER_LWP( K1D_Y, PTB_OBS, KSENS_ID, LD_MWAVE)

  ! Above a certain LWP threshold is designated as cloud
  IF (PLWP > YLCOEFF%ZLWP_LIMIT .OR. PLWP == RMDI) THEN 
    
    MWIMAGER_CLOUD = .TRUE. 
    LD_LWP = .TRUE. 

  ENDIF

  ! IF 37V is close enough to 37H, this suggests rain/snow
  IF (((PTB_OBS (YLCOEFF%I37V) + YLCOEFF%ZBBIAS) - PTB_OBS (YLCOEFF%I37H)) < &
    & RDTB_LIMIT) THEN
  
    MWIMAGER_CLOUD = .TRUE.
    LD_D37 = .TRUE. 
 
  ENDIF

ELSE

  CALL ABOR1(' MWIMAGER_CLOUD: Unknown instrument')

ENDIF

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

END FUNCTION MWIMAGER_CLOUD
