C Hp0.f
C
C VIS-5D function to calculate PERTURBATION first-guess of balanced geopotential
C height (Hp0)

C ==============================================================================

      INTEGER FUNCTION USERFUNC( OUTGRID, OUTNL, OUTLOWLEV,
     *                           INGRID, NR, NC, NL, LOWLEV, MAXNL,
     *                           NVARS, NAMES,
     *                           DATE, TIME,
     *                           PROJECTION, PROJ_ARGS,
     *                           VERTICAL, VERT_ARGS )
C ARGUMENTS:
      implicit none
      INTEGER NVARS
      INTEGER NR, NC, NL(NVARS), LOWLEV(NVARS), MAXNL
      REAL OUTGRID(NR,NC,MAXNL)
      INTEGER OUTNL, OUTLOWLEV
      REAL INGRID(NR,NC,MAXNL,NVARS)
      CHARACTER*8 NAMES(NVARS)
      INTEGER DATE, TIME
      INTEGER PROJECTION
      REAL PROJ_ARGS(*)
      INTEGER VERTICAL
      REAL VERT_ARGS(*)

C LOCAL VARS:
      integer var, ir, ic, il
      integer ih0, ihm0  

C ==============================================================================
      
C Specify number of levels in OUTGRID
      OUTNL = MAXNL
      OUTLOWLEV = 0
      
C Find the H0 and Hm0 variables (TOTAL and MEAN fields)
      ih0 = -1
      ihm0 = -1
      do var=1,nvars
        if (names(var) .eq. 'H0') ih0 = var
        if (names(var) .eq. 'Hm0') ihm0 = var        
      end do

C If H0 or Hm0 not found, return error 1
      if ( ih0.eq.-1 .or. ihm0.eq.-1 ) then
        print *, 
     $  "Couldn't find H0 or Hm0 vars!"
        userfunc = 1
        return
      endif

C ==============================================================================

C OUTPUT OF PERTURBATION FIRST-GUESS OF BALANCED GEOPOTENTIAL HEIGHT
C Hp0 (=H0-Hm0) 

      print*,
     $'Output of PERTURBATION first guess of balanced geopotential ',
     $'height Hp0 (m)'
      DO 9999 ir=1,nr
      DO 9999 ic=1,nc
      DO 9999 il=1,maxnl
        outgrid(ir,ic,il)=ingrid(ir,ic,il,ih0)-
     $                    ingrid(ir,ic,il,ihm0)
9999  CONTINUE     

C ==============================================================================
               
      USERFUNC = 0
      RETURN
      END

C ==============================================================================
