C OVLAPW.f
C
C VIS-5D analysis function to compute Overlap area favorable, 
C for convection developmet (W>0 at 700 hPa, Convective instability
C 1000-500, and water vapour flux convergence in 1000-700). No units


      INTEGER FUNCTION USERFUNC( OUTGRID, OUTNL, OUTLOWLEV,
     *                           INGRID, NR, NC, NL, LOWLEV, MAXNL,
     *                           NVARS, NAMES,
     *                           DATE, TIME,
     *                           PROJECTION, PROJ_ARGS,
     *                           VERTICAL, VERT_ARGS )
C     ARGUMENTS:
      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
      real p(22)

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

C    Find the forcing variables
      ifo = -1
      ici = -1
      iwv = -1
      do var=1,nvars
         if (names(var) .eq. 'W') ifo = var
         if (names(var) .eq. 'CI1050') ici = var
         if (names(var) .eq. 'WVFD70') iwv = var
      end do

C  If not found, return error 1
      if (ifo .eq. -1 .or. ici .eq. -1 .or. iwv.eq.-1) then
         print *, "Couldn't find W, CI1050, WVFD70 vars!"
         userfunc = 1
         return
      endif

	do i=1,maxnl
	p(i)=1012.5*exp(vert_args(i)/-7.2)
	if (p(i).gt.699.0.and.p(i).lt.701.) i85=i
	enddo
	
C  Compute Overlap
         do ic=1,nc
            do ir=1,nr
      do il=1,outnl
	if (ingrid(ir,ic,i85,ifo).gt.0.and.ingrid(ir,ic,1,ici).lt.0.
     & and.ingrid(ir,ic,1,iwv).lt.0) then
           outgrid(ir,ic,il)=Abs(ingrid(ir,ic,i85,ifo))*
     &Abs(ingrid(ir,ic,1,ici))*Abs(ingrid(ir,ic,1,iwv))
           outgrid(ir,ic,il)= outgrid(ir,ic,il)/1000.    
	else 
	   outgrid(ir,ic,il)=-Abs(ingrid(ir,ic,i85,ifo))*
     &Abs(ingrid(ir,ic,1,ici))*Abs(ingrid(ir,ic,1,iwv))
           outgrid(ir,ic,il)=outgrid(ir,ic,il)/1000.          
	endif
            end do
         end do
      end do

      USERFUNC = 0
      RETURN
      END
