C PT.f
C
C VIS-5D analysis function to compute Potential Temperature (in C)

C See example.f for more information about writing functions.


      INTEGER FUNCTION USERFUNC( OUTGRID, OUTNL, OUTLOWLEV,
     *                           INGRID, NR, NC, NL, LOWLEV, MAXNL,
     *                           NVARS, NAMES,
     *                           DATE, TIME,
     *                           PROJECTION, PROJ_ARGS,
     *                           VERTICAL, VERT_ARGS )
C     ARGUMENTS:
c      implicit none
   
      INTEGER NVARS
      INTEGER NR, NC, NL(NVARS), MAXNL
      REAL OUTGRID(NR,NC,MAXNL)
      INTEGER OUTNL
      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 it
      real tpot,t,p,rd,cp
      PARAMETER(rd=287.04,cp=1004.64)   


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

C   Find the T variables
      it = -1
      do var=1,nvars
         if (NAMES(var).eq."T") it = var
      end do
C   If T not found, return error 1
      if (it .eq. -1) then
         print *, "Couldn't find T variable!"
         userfunc = 1
         return
      endif

C     Compute 3-D Tpot
      do il=1,maxnl
         do ic=1,NC
            do ir=1,NR
               t = ingrid(ir,ic,il,it)
C              Check for missing data
               if (t .ge. 1.0e30) then
                  tpot = 1.0e35
               else
                  p=1012.5*exp(vert_args(il)/-7.2)
c                  print *,p
                  tpot = (t+273.16)*(1000./p)**(rd/cp)-273.16
               end if
               outgrid(ir,ic,il) = tpot
            end do
         end do
      end do

      USERFUNC = 0
      RETURN
      END
