! (C) Copyright 2001- ECMWF.
! (C) Copyright 2001- Meteo-France.
! 
! This software is licensed under the terms of the Apache Licence Version 2.0
! which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
! In applying this licence, ECMWF does not waive the privileges and immunities
! granted to it by virtue of its status as an intergovernmental organisation
! nor does it submit to any jurisdiction.
! 


MODULE ESPNORM_CTL_MOD
CONTAINS
SUBROUTINE ESPNORM_CTL(PSPEC,KFLD,KFLD_G,KVSET,KMASTER,PMET,PNORM)

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

USE TPM_DIM         ,ONLY : R
USE TPM_DISTR       ,ONLY : D, MYSETV, MYPROC

USE ESPNORMD_MOD    ,ONLY : ESPNORMD
USE SPNORMC_MOD     ,ONLY : SPNORMC

USE TPMALD_DIM      ,ONLY : RALD
!

IMPLICIT NONE

REAL(KIND=JPRB)    ,OPTIONAL, INTENT(IN)  :: PSPEC(:,:)
INTEGER(KIND=JPIM) ,OPTIONAL, INTENT(IN)  :: KVSET(:)
INTEGER(KIND=JPIM) ,OPTIONAL, INTENT(IN)  :: KMASTER
REAL(KIND=JPRB)    ,OPTIONAL, INTENT(IN)  :: PMET(:)
REAL(KIND=JPRB)    ,OPTIONAL, INTENT(OUT) :: PNORM(:)
INTEGER(KIND=JPIM)          , INTENT(IN)  :: KFLD,KFLD_G
INTEGER(KIND=JPIM) :: IVSET(KFLD_G)

REAL(KIND=JPRB)    :: ZMET(0:R%NSPEC_G)

REAL(KIND=JPRB)    :: ZSM(KFLD,D%NUMP)

REAL(KIND=JPRB)    :: ZGM(KFLD_G,0:RALD%NMSMAX)
REAL(KIND=JPHOOK) :: ZHOOK_HANDLE
REAL(KIND=JPHOOK) :: ZHOOK_HANDLE1

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

IF (LHOOK) CALL DR_HOOK('ESPNORM_CTL_MOD:ESPNORM_CTL',0,ZHOOK_HANDLE)
IF(PRESENT(KVSET)) THEN
  IVSET(:) = KVSET(:)
ELSE
  IVSET(:) = MYSETV
ENDIF

IF(PRESENT(PMET)) THEN
  ZMET(:) = PMET(:)
ELSE
  ZMET(:) = 1.0_JPRB
ENDIF

CALL ESPNORMD(PSPEC,KFLD,ZMET,ZSM)

IF (LHOOK) CALL DR_HOOK('ESPNORM_CTL_MOD:SPNORMC',0,ZHOOK_HANDLE1)
CALL SPNORMC(ZSM,KFLD_G,IVSET,KMASTER,RALD%NMSMAX,ZGM)
IF (LHOOK) CALL DR_HOOK('ESPNORM_CTL_MOD:SPNORMC',1,ZHOOK_HANDLE1)

IF(MYPROC == KMASTER) THEN
  PNORM(1:KFLD_G) = SUM(ZGM,DIM=2)
  PNORM(1:KFLD_G) = SQRT(PNORM(1:KFLD_G))
ENDIF
IF (LHOOK) CALL DR_HOOK('ESPNORM_CTL_MOD:ESPNORM_CTL',1,ZHOOK_HANDLE)
!     ------------------------------------------------------------------

END SUBROUTINE ESPNORM_CTL
END MODULE ESPNORM_CTL_MOD
