C AGL.f
C
C VIS-5D analysis function to compute Above Ground Level (in m), 
C using H and TERRAIN
	
      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(*),ter
C     LOCAL VARS:
      integer ir, ic, il
      integer igeo,var,ioro

      
C     Specify number of levels in OUTGRID
      OUTNL = MAXNL
      OUTLOWLEV = 0
     
C  Find the TERRAIN and H variables
      ioro = -1
      igeo = -1 
      do var=1,nvars
         if (NAMES(var).eq."TERRAIN") ioro = var
         if (names(var) .eq. 'H') igeo = var 
      end do
C  If TERRAIN or H not found, return error 1
      if (ioro.eq.-1 .or. igeo.eq.-1) then
         print *, "Couldn't find TERRAIN, H vars"
         userfunc = 1
         return
      endif
            
	do 100 ir=1,nr
	do 100 ic=1,nc
	ter=max(ingrid(ir,ic,1,ioro),0.)
	do 100 il=1,OUTNL
        outgrid(ir,ic,il)=ingrid(ir,ic,il,igeo)-ter 
100	enddo


      USERFUNC = 0
      RETURN

      END
