 SUBROUTINE POLATES1(IPOPT,KGDSI,KGDSO,MI,MO,KM,IBI,LI,GI, &
                     NO,RLAT,RLON,IBO,LO,GO,IRET)
!$$$  SUBPROGRAM DOCUMENTATION BLOCK
!
! $Revision: 71314 $
!
! SUBPROGRAM:  POLATES1   INTERPOLATE SCALAR FIELDS (BICUBIC)
!   PRGMMR: IREDELL       ORG: W/NMC23       DATE: 96-04-10
!
! ABSTRACT: THIS SUBPROGRAM PERFORMS BICUBIC INTERPOLATION
!           FROM ANY GRID TO ANY GRID FOR SCALAR FIELDS.
!           BITMAPS ARE NOW ALLOWED EVEN WHEN INVALID POINTS ARE WITHIN
!           THE BICUBIC TEMPLATE PROVIDED THE MINIMUM WEIGHT IS REACHED.
!           OPTIONS ALLOW CHOICES BETWEEN STRAIGHT BICUBIC (IPOPT(1)=0)
!           AND CONSTRAINED BICUBIC (IPOPT(1)=1) WHERE THE VALUE IS
!           CONFINED WITHIN THE RANGE OF THE SURROUNDING 16 POINTS.
!           ANOTHER OPTION IS THE MINIMUM PERCENTAGE FOR MASK,
!           I.E. PERCENT VALID INPUT DATA REQUIRED TO MAKE OUTPUT DATA,
!           (IPOPT(2)) WHICH DEFAULTS TO 50 (IF IPOPT(2)=-1).
!           BILINEAR USED WITHIN ONE GRID LENGTH OF BOUNDARIES.
!           ONLY HORIZONTAL INTERPOLATION IS PERFORMED.
!           THE GRIDS ARE DEFINED BY THEIR GRID DESCRIPTION SECTIONS
!           (PASSED IN INTEGER FORM AS DECODED BY SUBPROGRAM W3FI63).
!           THE CURRENT CODE RECOGNIZES THE FOLLOWING PROJECTIONS:
!             (KGDS(1)=000) EQUIDISTANT CYLINDRICAL
!             (KGDS(1)=001) MERCATOR CYLINDRICAL
!             (KGDS(1)=003) LAMBERT CONFORMAL CONICAL
!             (KGDS(1)=004) GAUSSIAN CYLINDRICAL (SPECTRAL NATIVE)
!             (KGDS(1)=005) POLAR STEREOGRAPHIC AZIMUTHAL
!             (KGDS(1)=203) ROTATED EQUIDISTANT CYLINDRICAL (E-STAGGER)
!             (KGDS(1)=205) ROTATED EQUIDISTANT CYLINDRICAL (B-STAGGER)
!           WHERE KGDS COULD BE EITHER INPUT KGDSI OR OUTPUT KGDSO.
!           AS AN ADDED BONUS THE NUMBER OF OUTPUT GRID POINTS
!           AND THEIR LATITUDES AND LONGITUDES ARE ALSO RETURNED.
!           ON THE OTHER HAND, THE OUTPUT CAN BE A SET OF STATION POINTS
!           IF KGDSO(1)<0, IN WHICH CASE THE NUMBER OF POINTS
!           AND THEIR LATITUDES AND LONGITUDES MUST BE INPUT.
!           OUTPUT BITMAPS WILL ONLY BE CREATED WHEN THE OUTPUT GRID
!           EXTENDS OUTSIDE OF THE DOMAIN OF THE INPUT GRID.
!           THE OUTPUT FIELD IS SET TO 0 WHERE THE OUTPUT BITMAP IS OFF.
!
! PROGRAM HISTORY LOG:
!   96-04-10  IREDELL
! 1999-04-08  IREDELL  SPLIT IJKGDS INTO TWO PIECES
! 2001-06-18  IREDELL  INCLUDE MINIMUM MASK PERCENTAGE OPTION
! 2007-05-22  IREDELL  EXTRAPOLATE UP TO HALF A GRID CELL
! 2007-10-30  IREDELL  CORRECT NORTH POLE INDEXING PROBLEM,
!                      UNIFY MASKED AND NON-MASKED ALGORITHMS,
!                      AND SAVE WEIGHTS FOR PERFORMANCE.
! 2012-06-26  GAYNO    FIX OUT-OF-BOUNDS ERROR.  SEE NCEPLIBS
!                      TICKET #9.
! 2015-01-27  GAYNO    REPLACE CALLS TO GDSWIZ WITH NEW MERGED
!                      VERSION OF GDSWZD.
!
! USAGE:    CALL POLATES1(IPOPT,KGDSI,KGDSO,MI,MO,KM,IBI,LI,GI,
!    &                    NO,RLAT,RLON,IBO,LO,GO,IRET)
!
!   INPUT ARGUMENT LIST:
!     IPOPT    - INTEGER (20) INTERPOLATION OPTIONS
!                IPOPT(1)=0 FOR STRAIGHT BICUBIC;
!                IPOPT(1)=1 FOR CONSTRAINED BICUBIC WHERE VALUE IS
!                CONFINED WITHIN THE RANGE OF THE SURROUNDING 4 POINTS.
!                IPOPT(2) IS MINIMUM PERCENTAGE FOR MASK
!                (DEFAULTS TO 50 IF IPOPT(2)=-1)
!     KGDSI    - INTEGER (200) INPUT GDS PARAMETERS AS DECODED BY W3FI63
!     KGDSO    - INTEGER (200) OUTPUT GDS PARAMETERS
!                (KGDSO(1)<0 IMPLIES RANDOM STATION POINTS)
!     MI       - INTEGER SKIP NUMBER BETWEEN INPUT GRID FIELDS IF KM>1
!                OR DIMENSION OF INPUT GRID FIELDS IF KM=1
!     MO       - INTEGER SKIP NUMBER BETWEEN OUTPUT GRID FIELDS IF KM>1
!                OR DIMENSION OF OUTPUT GRID FIELDS IF KM=1
!     KM       - INTEGER NUMBER OF FIELDS TO INTERPOLATE
!     IBI      - INTEGER (KM) INPUT BITMAP FLAGS
!     LI       - LOGICAL*1 (MI,KM) INPUT BITMAPS (IF SOME IBI(K)=1)
!     GI       - REAL (MI,KM) INPUT FIELDS TO INTERPOLATE
!     NO       - INTEGER NUMBER OF OUTPUT POINTS (ONLY IF KGDSO(1)<0)
!     RLAT     - REAL (NO) OUTPUT LATITUDES IN DEGREES (IF KGDSO(1)<0)
!     RLON     - REAL (NO) OUTPUT LONGITUDES IN DEGREES (IF KGDSO(1)<0)
!
!   OUTPUT ARGUMENT LIST:
!     NO       - INTEGER NUMBER OF OUTPUT POINTS (ONLY IF KGDSO(1)>=0)
!     RLAT     - REAL (MO) OUTPUT LATITUDES IN DEGREES (IF KGDSO(1)>=0)
!     RLON     - REAL (MO) OUTPUT LONGITUDES IN DEGREES (IF KGDSO(1)>=0)
!     IBO      - INTEGER (KM) OUTPUT BITMAP FLAGS
!     LO       - LOGICAL*1 (MO,KM) OUTPUT BITMAPS (ALWAYS OUTPUT)
!     GO       - REAL (MO,KM) OUTPUT FIELDS INTERPOLATED
!     IRET     - INTEGER RETURN CODE
!                0    SUCCESSFUL INTERPOLATION
!                2    UNRECOGNIZED INPUT GRID OR NO GRID OVERLAP
!                3    UNRECOGNIZED OUTPUT GRID
!
! SUBPROGRAMS CALLED:
!   GDSWZD       GRID DESCRIPTION SECTION WIZARD
!   IJKGDS0      SET UP PARAMETERS FOR IJKGDS1
!   (IJKGDS1)    RETURN FIELD POSITION FOR A GIVEN GRID POINT
!   POLFIXS      MAKE MULTIPLE POLE SCALAR VALUES CONSISTENT
!
! ATTRIBUTES:
!   LANGUAGE: FORTRAN 90
!
!$$$
!
 USE GDSWZD_MOD
!
 IMPLICIT NONE
!
 INTEGER,                INTENT(IN   ):: IPOPT(20),KGDSI(200)
 INTEGER,                INTENT(IN   ):: KGDSO(200),MI,MO,KM
 INTEGER,                INTENT(IN   ):: IBI(KM)
 INTEGER,                INTENT(INOUT):: NO
 INTEGER,                INTENT(  OUT):: IRET, IBO(KM)
!
 LOGICAL*1,              INTENT(IN   ):: LI(MI,KM)
 LOGICAL*1,              INTENT(  OUT):: LO(MO,KM)
!
 REAL,                   INTENT(IN   ):: GI(MI,KM)
 REAL,                   INTENT(INOUT):: RLAT(MO),RLON(MO)
 REAL,                   INTENT(  OUT):: GO(MO,KM)
!
 REAL,                   PARAMETER    :: FILL=-9999.
!
 INTEGER                              :: IJKGDSA(20)
 INTEGER                              :: IJX(4),IJY(4)
 INTEGER                              :: MCON,MP,N,I,J,K
 INTEGER                              :: NK,NV,IJKGDS1
 INTEGER,            SAVE             :: KGDSIX(200)=-1,KGDSOX(200)=-1
 INTEGER,            SAVE             :: NOX=-1,IRETX=-1
 INTEGER,            ALLOCATABLE,SAVE :: NXY(:,:,:),NC(:)
!
 REAL                                 :: PMP,XIJ,YIJ,XF,YF
 REAL                                 :: G,W,GMIN,GMAX
 REAL                                 :: WX(4),WY(4)
 REAL                                 :: XPTS(MO),YPTS(MO)
 REAL,               ALLOCATABLE,SAVE :: RLATX(:),RLONX(:),WXY(:,:,:)
! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
!  SET PARAMETERS
 IRET=0
 MCON=IPOPT(1)
 MP=IPOPT(2)
 IF(MP.EQ.-1.OR.MP.EQ.0) MP=50
 IF(MP.LT.0.OR.MP.GT.100) IRET=32
 PMP=MP*0.01
! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
!  SAVE OR SKIP WEIGHT COMPUTATION
 IF(IRET.EQ.0.AND.(KGDSO(1).LT.0.OR.ANY(KGDSI.NE.KGDSIX).OR.ANY(KGDSO.NE.KGDSOX))) THEN
! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
!  COMPUTE NUMBER OF OUTPUT POINTS AND THEIR LATITUDES AND LONGITUDES.
   IF(KGDSO(1).GE.0) THEN
     CALL GDSWZD(KGDSO, 0,MO,FILL,XPTS,YPTS,RLON,RLAT,NO)
     IF(NO.EQ.0) IRET=3
   ENDIF
! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
!  LOCATE INPUT POINTS
   CALL GDSWZD(KGDSI,-1,NO,FILL,XPTS,YPTS,RLON,RLAT,NV)
   IF(IRET.EQ.0.AND.NV.EQ.0) IRET=2
! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
!  ALLOCATE AND SAVE GRID DATA
   KGDSIX=KGDSI
   KGDSOX=KGDSO
   IF(NOX.NE.NO) THEN
     IF(NOX.GE.0) DEALLOCATE(RLATX,RLONX,NC,NXY,WXY)
     ALLOCATE(RLATX(NO),RLONX(NO),NC(NO),NXY(4,4,NO),WXY(4,4,NO))
     NOX=NO
   ENDIF
   IRETX=IRET
! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
!  COMPUTE WEIGHTS
   IF(IRET.EQ.0) THEN
     CALL IJKGDS0(KGDSI,IJKGDSA)
!$OMP PARALLEL DO PRIVATE(N,XIJ,YIJ,IJX,IJY,XF,YF,J,I,WX,WY)
     DO N=1,NO
       RLONX(N)=RLON(N)
       RLATX(N)=RLAT(N)
       XIJ=XPTS(N)
       YIJ=YPTS(N)
       IF(XIJ.NE.FILL.AND.YIJ.NE.FILL) THEN
         IJX(1:4)=FLOOR(XIJ-1)+(/0,1,2,3/)
         IJY(1:4)=FLOOR(YIJ-1)+(/0,1,2,3/)
         XF=XIJ-IJX(2)
         YF=YIJ-IJY(2)
         DO J=1,4
           DO I=1,4
             NXY(I,J,N)=IJKGDS1(IJX(I),IJY(J),IJKGDSA)
           ENDDO
         ENDDO
         IF(MINVAL(NXY(1:4,1:4,N)).GT.0) THEN
!  BICUBIC WHERE 16-POINT STENCIL IS AVAILABLE
           NC(N)=1
           WX(1)=XF*(1-XF)*(2-XF)/(-6.)
           WX(2)=(XF+1)*(1-XF)*(2-XF)/2.
           WX(3)=(XF+1)*XF*(2-XF)/2.
           WX(4)=(XF+1)*XF*(1-XF)/(-6.)
           WY(1)=YF*(1-YF)*(2-YF)/(-6.)
           WY(2)=(YF+1)*(1-YF)*(2-YF)/2.
           WY(3)=(YF+1)*YF*(2-YF)/2.
           WY(4)=(YF+1)*YF*(1-YF)/(-6.)
         ELSE
!  BILINEAR ELSEWHERE NEAR THE EDGE OF THE GRID
           NC(N)=2
           WX(1)=0
           WX(2)=(1-XF)
           WX(3)=XF
           WX(4)=0
           WY(1)=0
           WY(2)=(1-YF)
           WY(3)=YF
           WY(4)=0
         ENDIF
         DO J=1,4
           DO I=1,4
             WXY(I,J,N)=WX(I)*WY(J)
           ENDDO
         ENDDO
       ELSE
         NC(N)=0
       ENDIF
     ENDDO
   ENDIF
 ENDIF
! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
!  INTERPOLATE OVER ALL FIELDS
 IF(IRET.EQ.0.AND.IRETX.EQ.0) THEN
   IF(KGDSO(1).GE.0) THEN
     NO=NOX
     DO N=1,NO
       RLON(N)=RLONX(N)
       RLAT(N)=RLATX(N)
     ENDDO
   ENDIF
!$OMP PARALLEL DO PRIVATE(NK,K,N,G,W,GMIN,GMAX,J,I)
   DO NK=1,NO*KM
     K=(NK-1)/NO+1
     N=NK-NO*(K-1)
     IF(NC(N).GT.0) THEN
       G=0
       W=0
       IF(MCON.GT.0) GMIN=HUGE(GMIN)
       IF(MCON.GT.0) GMAX=-HUGE(GMAX)
       DO J=NC(N),5-NC(N)
         DO I=NC(N),5-NC(N)
           IF(NXY(I,J,N).GT.0)THEN
             IF(IBI(K).EQ.0.OR.LI(NXY(I,J,N),K))THEN
               G=G+WXY(I,J,N)*GI(NXY(I,J,N),K)
               W=W+WXY(I,J,N)
               IF(MCON.GT.0) GMIN=MIN(GMIN,GI(NXY(I,J,N),K))
               IF(MCON.GT.0) GMAX=MAX(GMAX,GI(NXY(I,J,N),K))
             ENDIF
           ENDIF
         ENDDO
       ENDDO
       LO(N,K)=W.GE.PMP
       IF(LO(N,K)) THEN
         GO(N,K)=G/W
         IF(MCON.GT.0) GO(N,K)=MIN(MAX(GO(N,K),GMIN),GMAX)
       ELSE
         GO(N,K)=0.
       ENDIF
     ELSE
       LO(N,K)=.FALSE.
       GO(N,K)=0.
     ENDIF
   ENDDO
   DO K=1,KM
     IBO(K)=IBI(K)
     IF(.NOT.ALL(LO(1:NO,K))) IBO(K)=1
   ENDDO
   IF(KGDSO(1).EQ.0) CALL POLFIXS(NO,MO,KM,RLAT,RLON,IBO,LO,GO)
! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 ELSE
   IF(IRET.EQ.0) IRET=IRETX
   IF(KGDSO(1).GE.0) NO=0
 ENDIF
! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 END SUBROUTINE POLATES1


MODULE compute_profile_error

IMPLICIT NONE

! The cmpTz subroutine in this module uses the 3DVar-GODAS method to
! estimate the vertical error distribution for temperature (or salinity)
! profiles. The errors are based on the gradient of the profile at each depth
! using a centered-difference estimate.
!
! NOTE: The code ASSUMES that the profiles are only defined on the model grid
!       levels. The behavoir when that is not the case (e.g. if the raw observation
!       profiles were used) is unknown.
!
! Authors:
!       Steve Penny
!       David Behrginger (Original author of C code on which this module is based)
!

! the vertical temperature gradient is rescaled to vary between 0.0 and 1.0
! so to set the std errors ultimately between 1.0 and 2.5 use
! SE0 = 1.0 and SEF = 1.5
! then EVR = 1/(se*se)
! if std error = 0.5, then EVR = 4.0
!                1.0             1.0
!                1.5             0.4444
!
REAL,    PARAMETER :: maxerr = 999.0 !STEVE: large number assigned as max error
REAL,    PARAMETER :: teps = 0.00005 !epsilon(1.0)  !STEVE: a small number
INTEGER, PARAMETER :: kav = 5        !STEVE: indicates how many gridpoints to use in the vetical averaging
!LOGICAL :: DO_SCALEDZ=.false.
LOGICAL :: DO_SQRT=.false.
LOGICAL :: dodebug=.false.

PUBLIC :: cmpTz

CONTAINS

! Compute the gradient of t at the model levels. Also perform some other computations
! tz is the scaling to apply to the se error profiles
! a contains 1 / se**2

SUBROUTINE cmpTz(se,se0,seF,t,z,kd,spv)
  USE common, ONLY: r_size
  INTEGER ::  k, kk, km, kp, kv2, cnt
  REAL :: tzmn, tzmx
  REAL(r_size),DIMENSION(kd), INTENT(OUT) :: se  ! standard deviations (errors)
  REAL(r_size), INTENT(IN) :: se0
  REAL(r_size), INTENT(IN) :: seF
  REAL(r_size),DIMENSION(kd), INTENT(IN)  :: t   ! temperature values
  REAL(r_size),DIMENSION(kd), INTENT(IN)  :: z   ! depths
  INTEGER, INTENT(IN) :: kd              ! total number (depth) of levels
  REAL(r_size), INTENT(IN) :: spv ! Spurious/missing value
  REAL,DIMENSION(kd) :: tz, tw

  if (dodebug) then
    print *, "============================================"
    print *, "Inputs ::"
    print *, "t   = ", t
    print *, "z   = ", z
    print *, "kd  = ", kd
    print *, "spv = ", spv
    print *, "============================================"
  endif

  ! Check input quality:
  if (MAXVAL(z) < TINY(1.0d0)) then
    print *, "cmpTz :: input depths are zero, check input arguments. EXITING..."
    STOP(13)
  endif

  ! Estimate profile gradients
  ! i.e. every level is linearly fit from below and above
  do k = 2,kd-1
    if (t(k-1) /= spv .AND. t(k+1) /= spv) then
      ! Estimate profile gradient with centered-difference scheme
      tz(k) = (t(k-1) - t(k+1)) / (z(k+1) - z(k-1))
      ! ensure non-negative gradient
      if (tz(k) < 0.0) then
        tz(k) = 0.0
      endif
    else
      tz(k) = spv
    endif
  enddo
  tz(1) = spv
  tz(kd) = spv

  ! For all levels with obs data,
  ! Fix levels in which gradients end up as spurious values (most likely due to missing values in obs data)
  ! Use 'nearest neighbor' method to assign the gradient value
  do k = 1,kd

    ! if one of the values was computed with a missing value, then
    ! we have to go back and find the nearest non-missing value to do the computation of the gradient
    if (tz(k) == spv .AND. t(k) /= spv) then

      ! k minus
      km = -1;
      ! Go back to the first non-missing value
      do kk = k,-1,1
        if (tz(kk) /= spv) then
          km = kk
          exit
        endif
      enddo

      ! k plus
      kp = kd;
      ! Go forward to the first non-missing value
      do kk = k+1,kd-1
        if (tz(kk) /= spv) then
          kp = kk
          exit
        endif
      enddo

      ! if k-minus and k-plus are in the range of observed levels,
      if (km >= 1 .AND. kp <= kd) then

        ! assign the value to level k of the nearest neighbor (km or kp)
        if (k-km <= kp-k) then
          tz(k) = tz(km)
        else
          tz(k) = tz(kp)
        endif

      ! otherwise, handle the boundary cases
      elseif (km >= 1) then
        tz(k) = tz(km)
      elseif (kp <= kd) then
        tz(k) = tz(kp)
      else
        tz(k) = spv
      endif

    endif
  enddo

  do k = 1,kd
    if (tz(k) == spv .AND. t(k) /= spv) then
      tz(k) = 0.0
    endif
  enddo

  if (DO_SQRT) then
    ! take square root of tz
    WHERE(tz /= spv .AND. tz > 0.0) tz = SQRT(tz)
  endif

  !STEVE: This averages consecutive tz's to smooth out the observation errors
  ! kav identifies how many gridpoints to use in the averaging window.
  if (kav > 1) then
    kv2 = kav / 2
    do k = 1, kd
      if (tz(k) /= spv) then
        if (k-kv2 >= 1) then
          km = k-kv2
        else
          km = 1
        endif
        cnt = 1;
        tw(k) = tz(k)
        do kk = k-1,-1,km
          if (tz(kk) /= spv) then
            tw(k) = tw(k) + tz(kk)
            cnt=cnt+1
          else
            exit
          endif
        enddo

        if (k+kv2 <= kd) then
          kp = k+kv2
        else
          kp = kd
        endif
        do kk = k+1,kp
          if (tz(kk) /= spv) then
            tw(k) = tw(k) + tz(kk)
            cnt=cnt+1
          else
            exit
          endif
        enddo
        if (cnt>1) then
          tw(k) = tw(k)/REAL(cnt);
        endif
      else
        tw(k) = spv
      endif
    enddo
    do k = 1,kd
      tz(k) = tw(k)
    enddo
  endif

  ! Find the minimum and maximum tz, and rescale so tz is between
  ! 0 and 1, before applying to the errors
  if (dodebug) print *, "pre-rescaled tz = ", tz
  tzmn = abs(spv);
  tzmx = -abs(spv);
  do k = 1,kd
    if (tz(k) /= spv) then
      if (tzmn >= tz(k)) then
        tzmn = tz(k)
      endif
      if (tzmx <= tz(k)) then
        tzmx = tz(k)
      endif
    endif
  enddo
  tzmx = tzmx-tzmn
  if (dodebug) then
    print *, "tzmn = ", tzmn
    print *, "tzmx = ", tzmx
  endif
  if (tzmx < teps) then
    WHERE (tz /= spv) tz = 0.0
    if (dodebug) print *, "WARNING :: zeroed out tz"
  else
    do k = 1,kd
      if (tz(k) /= spv) then
        tz(k) = tz(k)-tzmn
        tz(k) = tz(k)/tzmx
      endif
    enddo
  endif
  if (dodebug) print *, "post-rescaled tz = ", tz

  ! tz is used only for scaling the standard deviation (error) by depth, so it's not needed
  ! if the observational errors are read in from the netcdf obs file

  if (dodebug) print *, "t  = ", t
  if (dodebug) print *, "tz = ", tz
  do k = 1,kd
    if (t(k) /= spv) then
      ! specify the standard deviation (obs error)
      ! The result is scaled in the range
      ! from se0 to se0+seF.
      se(k) = se0 + seF * tz(k)
    else
      se(k) = maxerr
    endif

    !STEVE: check for NaN's, if we have one, assign average of se0 and seF as error
    if(se(k) /= se(k)) then !NaN check
      se(k) = (se0+se0+seF)/2.0 !STEVE: temporary fix (ISSUE)
    endif

  enddo
  if (dodebug) print *, "se = ", se

END SUBROUTINE cmpTz

END MODULE compute_profile_error