C I_Sp.f
C
C VIS-5D function to calculate PERTURBATION balanced streamfunction (I_Sp)

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 ii_s, ii_sm  

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

C If I_S or I_Sm not found, return error 1
      if ( ii_s.eq.-1 .or. ii_sm.eq.-1 ) then
        print *, 
     $  "Couldn't find I_S or I_Sm vars!"
        userfunc = 1
        return
      endif

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

C OUTPUT OF PERTURBATION BALANCED STREAMFUNCTION I_Sp (=I_S-I_Sm) 

      print*,
     $'Output of PERTURBATION balanced streamfunction ',
     $'I_Sp ([grav/Fndim] m2 s-1)'
      DO 9999 ir=1,nr
      DO 9999 ic=1,nc
      DO 9999 il=1,maxnl
        outgrid(ir,ic,il)=ingrid(ir,ic,il,ii_s)-
     $                    ingrid(ir,ic,il,ii_sm)
9999  CONTINUE     

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

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