C ErPVp.f
C
C VIS-5D function to calculate PERTURBATION 3-D Ertel PV distribution (ErPVp)

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 ierpv, ierpvm  

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

C If ErPV or ErPVm not found, return error 1
      if ( ierpv.eq.-1 .or. ierpvm.eq.-1 ) then
        print *, 
     $  "Couldn't find ErPV or ErPVm vars!"
        userfunc = 1
        return
      endif

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

C OUTPUT OF PERTURBATION 3-D ERTEL PV DISTRIBUTION ErPVp (=ErPV-ErPVm)

      print*,
     $'Output of PERTURBATION 3-D Ertel PV distribution ErPVp (PVU)'
      DO 9999 ir=1,nr
      DO 9999 ic=1,nc
      DO 9999 il=1,maxnl
        outgrid(ir,ic,il)=ingrid(ir,ic,il,ierpv)-
     $                    ingrid(ir,ic,il,ierpvm)
9999  CONTINUE     

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

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