C LR8550.f
C
C VIS-5D analysis function to compute Lapse Rate between 850 and 500
C (in K/km)

      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 ig,il850,il500,it
	real p

C     Specify number of levels in OUTGRID
      OUTNL = 1
      OUTLOWLEV = 0

C     Find the H and T variables
      ig = -1
      do var=1,nvars
         if (names(var) .eq. 'H') ig = var
         if (names(var) .eq. 'T') it = var
      end do
      
C  If H, or T not found, return error 1
      if (ig.eq.-1 .or. it.eq.-1) then
         print *, "Couldn't find H or T variables!"
         userfunc = 1
         return
      endif
           
      do il=1,maxnl
       p=1012.5*exp(vert_args(il)/-7.2)
       If ((p.Gt.849.).And.(p.Lt.851.)) Then
        il850=il
       Endif
       If ((p.Gt.499.).And.(p.Lt.501.)) Then
        il500=il
       Endif
      enddo

C     Compute espessor in K/km
         do ic=1,nc
            do ir=1,nr
		do il=1,outnl		
               outgrid(ir,ic,il) =(ingrid(ir,ic,il850,it)-
     & ingrid(ir,ic,il500,it))/(ingrid(ir,ic,il500,ig)-
     & ingrid(ir,ic,il850,ig))*1000
		enddo
            end do
         end do
	print*,'Units of K/km'
      USERFUNC = 0
      RETURN
      END
