SUBROUTINE RDCLIM(NCID)
USE PARKIND1  ,ONLY : JPIM     ,JPRB

#ifdef DOC

!**** *RDCLIM * - Reading netCDF file containing surface climate fields

!     Purpose.
!     --------
!            initialization surface characteristics

!**   Interface.
!     ----------
!        *CALL* *RDCLIM(NCID)

!     Explicit arguments :
!     --------------------
!     NCID      INT     NetCDF file code


!        Implicit arguments :
!        --------------------


!     Method.
!     -------
!       Opens a file called 'surfclim' to read relevant fields
!       In the file, fields are assumed to be stored as 
!           FIELD(LAT,LON)
!       or
!           FIELD(MONTH,LAT,LON)
!       or
!           FIELD(MONTH,VTYPE,LAT,LON) In this case, the climatology is given
!           for each vegetation type (20) and bare soil.


!     Externals.
!     ----------
!       NETCDF-utilities

!     Reference.
!     ----------

!     Author.
!     -------
!        Bart vd Hurk, KNMI

!     Modifications.
!     --------------
!        Original : 2000-07-07
!     E. Dutra  07/14/2008  : Reading lake related fields (depth and cover) 
!     E. Dutra  17/11/2009  : Reading LAI fields
!     S. Boussetta/G.Balsamo May 2010 Add CTESSEL based on:  
!	 Marita Voogt (KNMI) new tiling (13), vegetation types (7)
!                            and climatology (dec 2004)
!        Sebastien LAFONT (ECMWF) LAI,fract,Z0 are read for all the vegetation type
!                                 Then the value are computed only 
!                                 for the dominant low and dominant high 
!      E. Dutra 07/2014 : netcdf4 

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

#endif

USE YOMGPD1S , ONLY : GPD &
                     &,VFZ0F,VFALBF,VFZ0H,VFITM,VFGEO &
                     &,VFALUVP,VFALUVD,VFALNIP,VFALNID &
                     &,VFCVL &
                     &,VFCVH,VFTVL,VFTVH,VFSST,VFCI,VFSOTY &
                     &,VFSDOR&
                     &,VFLDEPTH,VFCLAKE &
                     &,VFZO,VFHO,VFHO_INV,VFDO,VFOCDEPTH,VFADVT &
                     &,VFADVS, VFTRI0, VFTRI1, VFSWDK_SAVE &
                     &,VFLAIL,VFLAIH,VFRSML,VFRSMH,VFR0VT &
                     &,VFSOALUVP,VFSOALUVD,VFSOALNIP,VFSOALNID,VFPGLOB
USE YOMCC1S  , ONLY : GPCC,VCALB,VCLAIL,VCLAIH
USE YOMGC1S  , ONLY : LMASK
USE YOMDPHY  , ONLY : NLON, NLAT, NPOI, NVSF, NGCC, NLALO  ,NVHILO, NCLIMDAT
USE YOMLUN1S , ONLY : NULOUT, RMISS
USE YOMLOG1S , ONLY : NDIMCDF
USE YOEPHY   , ONLY : LELAIV
USE NETCDF
USE NETCDF_UTILS, ONLY: NCERROR
USE YOMECEARTH, ONLY : LRDALB
IMPLICIT NONE

#include "minmax.intfb.h"

!* Arguments
INTEGER(KIND=JPIM),INTENT(IN) :: NCID

!* NetCDF interface
INTEGER ISTART2(2),ICOUNT2(2)
INTEGER ISTART3(3),ICOUNT3(3)
INTEGER ISTART4(4),ICOUNT4(4)
REAL(KIND=JPRB),ALLOCATABLE :: ZREALD(:)
REAL(KIND=JPRB),ALLOCATABLE :: ZREAL3D(:,:)
REAL(KIND=JPRB),ALLOCATABLE :: ZREAL4D(:,:,:)
INTEGER NILON,NIDLON,NILAT,NIDLAT,IERR,NIDMON,NIMON,NVARID,NVARTYP,NIDVT,NIVT
INTEGER NDIMS(100),NVDIMS,NVATTS
INTEGER NDIM, NVARS, NGATTS, IRECDIM
CHARACTER*100 CNAME
CHARACTER*8 CDUM

REAL(KIND=JPRB),ALLOCATABLE :: ZLAIVT(:,:,:)
REAL(KIND=JPRB),ALLOCATABLE :: ZCVT1(:,:)
REAL(KIND=JPRB) :: ZR0VT(NPOI,NVHILO)

!* Other variables
INTEGER(KIND=JPIM) :: NMX,NMY,IMON,JL,J,JMO,JMON,IVAR,JVT,JD,DIMLEN,STATUS,IVARP
LOGICAL LOPRES
INTEGER(KIND=JPIM)           :: NVARS2D
CHARACTER(LEN=20)            :: CVARS2D(40),CVAR

DATA ISTART2/1,1/
DATA ISTART3/1,1,1/
DATA ISTART4/1,1,1,1/

!* check the dimensions

CALL NCERROR (NF90_INQUIRE(NCID, nDimensions=NDIM,nVariables=NVARS),'FINDING N DIMS')

NILON=-999
NILAT=-999
DO JD=1,NDIM
  CALL NCERROR(NF90_INQUIRE_DIMENSION(NCID, JD, name=CNAME, len=DIMLEN),'INQ DIMENSION')
  SELECT CASE (TRIM(CNAME))
    CASE('x','lon')
      NILON=DIMLEN
      WRITE(NULOUT,*)'DIMENSION x ',TRIM(CNAME),' FOUND WITH LEN=',NILON
   CASE('y','lat')
      NILAT=DIMLEN
      WRITE(NULOUT,*)'DIMENSION y ',TRIM(CNAME),' FOUND WITH LEN=',NILAT
   CASE('month')
      NIMON=DIMLEN
      WRITE(NULOUT,*)'DIMENSION month ',TRIM(CNAME),' FOUND WITH LEN=',NIMON
  END SELECT
END DO
IF (NDIMCDF == 1 ) THEN
  NILAT = 0
ENDIF

!NIDVT = NCDID(NCID, 'nvtiles', IERR)
!CALL NCDINQ(NCID,NIDVT,CNAME,NIVT,IERR)
NIVT=2

IF(NILON /= NLON .OR. NILAT /= NLAT) THEN
  WRITE(NULOUT,*)'NLON OR NLAT NOT SPECIFIED CORRECTLY:'
  WRITE(NULOUT,*)'NLON IN NAMELIST AND SURFCLIM: ',NLON,NILON
  WRITE(NULOUT,*)'NLAT IN NAMELIST AND SURFCLIM: ',NLAT,NILAT
  CALL ABORT
ENDIF

IF(NIMON /= NCLIMDAT) THEN
  WRITE(NULOUT,*)'NMONTH IN SURFCLIM UNEQUAL TO ',NCLIMDAT
  CALL ABORT
ENDIF
IF(NIVT /= NVHILO) THEN
  WRITE(NULOUT,*)'NVHILO IN SURFCLIM UNEQUAL TO ',NVHILO
  CALL ABORT
ENDIF



!* Note the reversal of the order of array storage

IF(NDIMCDF == 2)THEN
  ICOUNT2(1)=NILON
  ICOUNT2(2)=NILAT

  ICOUNT3(1)=NILON
  ICOUNT3(2)=NILAT
  ICOUNT3(3)=NCLIMDAT

  ICOUNT4(1)=NILON
  ICOUNT4(2)=NILAT
  ICOUNT4(3)=NVHILO
  ICOUNT4(4)=NCLIMDAT

  NMX=NLON
  NMY=NLAT
ELSE
  ICOUNT2(1)=NILON

  ICOUNT3(1)=NILON
  ICOUNT3(2)=NCLIMDAT

  ICOUNT4(1)=NILON
  ICOUNT4(2)=NVHILO
  ICOUNT4(3)=NCLIMDAT

  NMX=NLALO
  NMY=1
ENDIF

ALLOCATE (ZREALD(NLALO))
ALLOCATE (ZREAL3D(NLALO,NCLIMDAT))
ALLOCATE (ZREAL4D(NLALO,NVHILO,NCLIMDAT))
ALLOCATE (ZLAIVT(NPOI,NVHILO,NCLIMDAT))


!* Read surface climate values

!* -- albedo
IF ( LRDALB) THEN
  CALL NCERROR( NF90_INQ_VARID(NCID, 'Malbedo', NVARID),'getting varid Malbedo' )
  CALL NCERROR( NF90_GET_VAR(NCID,NVARID,ZREAL3D,ISTART3,ICOUNT3),'READING Malbedo')
  DO JMON=1,NCLIMDAT
    WRITE(CDUM,'(A6,I2.2)')'ALBEDO',JMON
    ZREALD(:)=ZREAL3D(:,JMON)
    CALL MINMAX(CDUM,ZREALD,NMX,NMY,LMASK,NULOUT)
    VCALB(:,JMON)=PACK(ZREAL3D(:,JMON),LMASK)
  ENDDO
  VFALBF(:)=SUM(VCALB,DIM=2)/NCLIMDAT
ELSE
  VCALB(:,:)=0.01_JPRB
  VFALBF(:)=0.01_JPRB 
ENDIF
VFALUVP=VFALBF
VFALUVD=VFALBF
VFALNIP=VFALBF
VFALNID=VFALBF
  
! 
! !* LAI
IF (LELAIV) THEN
  STATUS = NF90_INQ_VARID(NCID, 'Mlail', NVARID)
  IF ( STATUS /= 0 ) THEN
    WRITE(NULOUT,'(A)')'Mlail NOT PRESENT IN INPUT FILE'
    WRITE(NULOUT,'(A)')'PUT LELAIV TO FALSE IN NAMELIST OR ADD FIELD TO CLIM NETCDF'
    CALL ABORT
  ENDIF
  CALL NCERROR( NF90_GET_VAR(NCID,NVARID,ZREAL3D,ISTART3,ICOUNT3),'READING Mlail')
  DO JMON=1,NCLIMDAT
      WRITE(CDUM,'(A4,I2.2)')'LAIL',JMON
       ZREALD(:)=ZREAL3D(:,JMON)
      CALL MINMAX(CDUM,ZREALD,NMX,NMY,LMASK,NULOUT)
      VCLAIL(:,JMON)=PACK(ZREAL3D(:,JMON),LMASK)
  ENDDO
  CALL NCERROR( NF90_INQ_VARID(NCID, 'Mlaih', NVARID),'getting varid Mlaih' )
  CALL NCERROR( NF90_GET_VAR(NCID,NVARID,ZREAL3D,ISTART3,ICOUNT3),'READING Mlaih')
  DO JMON=1,NCLIMDAT
      WRITE(CDUM,'(A4,I2.2)')'LAIH',JMON
      ZREALD(:)=ZREAL3D(:,JMON)
      CALL MINMAX(CDUM,ZREALD,NMX,NMY,LMASK,NULOUT)
      VCLAIH(:,JMON)=PACK(ZREAL3D(:,JMON),LMASK)
  ENDDO
  VFLAIL(:)=SUM(VCLAIL,DIM=2)/NCLIMDAT
  VFLAIH(:)=SUM(VCLAIH,DIM=2)/NCLIMDAT    
ELSE
  VCLAIH(:,:)=0._JPRB
  VCLAIL(:,:)=0._JPRB
  VFLAIL(:)=0._JPRB
  VFLAIH(:)=0._JPRB
ENDIF

!* -- vegetation coverage
!  not in climate fields, but calculated from LAI.
! not used in CTESSEL
DO JL=1,NPOI
    VFRSML(JL)=0._JPRB
    VFRSMH(JL)=0._JPRB
ENDDO

!! 2D FIELDS
NVARS2D=15
 CVARS2D(1:NVARS2D)=(/'z0m    ','lz0h   ','landsea','geopot ','cvl    ', &
                      'cvh    ','tvl    ','tvh    ','sotype ','sdor   ',&
                      'sst    ','seaice ','LDEPTH ','CLAKE  ','x      '/)
IF (.NOT.LRDALB) THEN
 IVARP=NVARS2D
 NVARS2D=NVARS2D+4
 CVARS2D(IVARP+1:NVARS2D)=(/'soaluvp','soaluvd','soalnip','soalnid'/)
ENDIF
  

DO IVAR=1,NVARS2D
  CVAR=TRIM(CVARS2D(IVAR))
  STATUS = NF90_INQ_VARID(NCID, CVAR, NVARID)
  IF ( STATUS /= 0 ) THEN
    WRITE(NULOUT,'(A)') CVAR//' NOT PRESENT IN INPUT FILE'
  ELSE
    CALL NCERROR( NF90_GET_VAR(NCID,NVARID,ZREALD,ISTART2,ICOUNT2),'READING '//CVAR)
  ENDIF
  SELECT CASE(CVAR)
    CASE('z0m')
       IF ( STATUS /= 0 ) ZREALD(:) = 1.
       VFZ0F=PACK(ZREALD,LMASK)
    CASE('lz0h')
       IF ( STATUS /= 0 ) ZREALD(:) = 1.
       VFZ0H=EXP(PACK(ZREALD,LMASK))
    CASE('landsea')
      IF ( STATUS /= 0 ) CALL ABORT
      VFITM=PACK(ZREALD,LMASK)
    CASE('geopot')
      IF ( STATUS /= 0 ) ZREALD(:) = 0.
      VFGEO=PACK(ZREALD,LMASK)
    CASE('cvl')
      IF ( STATUS /= 0 ) CALL ABORT
      VFCVL=PACK(ZREALD,LMASK)
    CASE('cvh')
      IF ( STATUS /= 0 ) CALL ABORT
      VFCVH=PACK(ZREALD,LMASK)
    CASE('tvl')
      IF ( STATUS /= 0 ) CALL ABORT
      VFTVL=PACK(ZREALD,LMASK)
    CASE('tvh')
      IF ( STATUS /= 0 ) CALL ABORT
      VFTVH=PACK(ZREALD,LMASK)
    CASE('sotype')
      IF ( STATUS /= 0 ) CALL ABORT
      VFSOTY=PACK(ZREALD,LMASK)
    CASE('sdor')
      IF ( STATUS /= 0 ) CALL ABORT
      VFSDOR=PACK(ZREALD,LMASK)
    CASE('soaluvd')
      IF ( STATUS /= 0 ) CALL ABORT
      VFSOALUVD=PACK(ZREALD,LMASK)
    CASE('soaluvp')
      IF ( STATUS /= 0 ) CALL ABORT
      VFSOALUVP=PACK(ZREALD,LMASK)
    CASE('soalnid')
      IF ( STATUS /= 0 ) CALL ABORT
      VFSOALNID=PACK(ZREALD,LMASK)
    CASE('soalnip')
      IF ( STATUS /= 0 ) CALL ABORT
      VFSOALNIP=PACK(ZREALD,LMASK)
    CASE('sst')
      IF ( STATUS /= 0 ) ZREALD(:) = 288.15
      VFSST=PACK(ZREALD,LMASK)
    CASE('seaice')
      IF ( STATUS /= 0 ) ZREALD(:) = 0.
      VFCI=PACK(ZREALD,LMASK)
    CASE('LDEPTH')
      IF ( STATUS /= 0 ) ZREALD(:) = 10.
      VFLDEPTH=PACK(ZREALD,LMASK)
    CASE('CLAKE')
       IF ( STATUS /= 0 ) ZREALD(:) = 0.
       VFCLAKE=PACK(ZREALD,LMASK)
    CASE('x')
       IF ( STATUS /= 0 ) ZREALD(:) = -1
       VFPGLOB=(PACK(ZREALD,LMASK))
    CASE DEFAULT
      WRITE(NULOUT,*) CVAR, ' Not defined in RDCLIM'
      CALL ABORT()
  END SELECT
  CALL MINMAX(CVAR,ZREALD,NMX,NMY,LMASK,NULOUT)
ENDDO

IF (LRDALB) THEN
  VFSOALNID=0.01_JPRB
  VFSOALNIP=0.01_JPRB
  VFSOALUVD=0.01_JPRB
  VFSOALUVP=0.01_JPRB
ENDIF 

!* -- reference respiration
! 3rd dimension is now NVHILO instead of month

DEALLOCATE (ZREAL3D)
ALLOCATE (ZREAL3D(NLALO,NVHILO))
IF(NDIMCDF == 2)THEN
  ICOUNT3(3)=NVHILO
ELSE
  ICOUNT3(2)=NVHILO
ENDIF
STATUS = NF90_INQ_VARID(NCID, 'r0vt', NVARID)
IF ( STATUS /= 0 ) THEN
  ZREAL3D(:,:)=0.145E-06_JPRB
  WRITE(NULOUT,'(A)')'R0VT NOT PRESENT IN INPUT FILE NOW SET TO 0.145E-06 kg CO2/m2/s'
  WRITE(NULOUT,'(A)')'PUT LECTESSEL TO FALSE IN NAMELIST OR ADD R0VT FIELD TO CLIM NETCDF'
ELSE
  CALL NCERROR( NF90_GET_VAR(NCID,NVARID,ZREAL3D,ISTART3,ICOUNT3),'READING '//CVAR)
ENDIF
DO JVT=1,NVHILO
  WRITE(CDUM,'(A4,I2.2)')'R0VT',JVT
  ZREALD(:)=ZREAL3D(:,JVT)
  CALL MINMAX(CDUM,ZREALD,NMX,NMY,LMASK,NULOUT)
  VFR0VT(:,JVT)=PACK(ZREAL3D(:,JVT),LMASK)
ENDDO  


VFZO(:,:)=0.
VFHO(:,:)=0.
VFHO_INV(:,:)=0.
VFDO(:,:)=0.
VFOCDEPTH(:)=0.
VFADVT(:,:)=0.
VFADVS(:,:)=0.
VFTRI0(:,:)=0.
VFTRI1(:,:)=0.
VFSWDK_SAVE(:,:)=0.
WRITE(NULOUT,*) 'RDCLIM CALLED, VFTRI, VFSWDK_SAVE, VFOCDEPTH... RESET'

!* Check final values

DO JL=1,NPOI
  DO J=1,NVSF
    IF (GPD(JL,J) == -999.) THEN
      WRITE(NULOUT,*) 'UNCORRECT SURFACE PROPERTIES IN RDCLIM'
      WRITE(NULOUT,*)JL,J
      CALL ABORT
    ENDIF
  ENDDO
  DO J=1,NGCC
    DO JMO=1,NCLIMDAT
      IF (GPCC(JL,jmo,J) == -999.) THEN
        WRITE(NULOUT,*)'UNCORRECT SURFACE SEASONAL PROPERTIES IN RDCLIM'
        CALL ABORT
      ENDIF
    ENDDO
  ENDDO
ENDDO

DEALLOCATE (ZREALD)
DEALLOCATE (ZREAL3D)
DEALLOCATE (ZREAL4D)
DEALLOCATE (ZLAIVT)

END SUBROUTINE RDCLIM
