C DIVUV.f

C VIS-5D analysis function to compute the horizontal wind divergence
C (in 1.E-5 s-1)

      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,imap
      integer iu, iv
      real Pi,Rt,escal,ds
      parameter (Pi=3.141596,Rt=6371227.,escal=1.e5)

C     Specify number of levels in OUTGRID
	print*,'Divergencia reescalada en 1.e5'
      OUTNL = MAXNL
      OUTLOWLEV = 0

C     Find the U, V and MAPFACCR variables
      iu = -1
      iv = -1
      imap = -1
      do var=1,nvars
         if (names(var) .eq. 'U') iu = var
         if (names(var) .eq. 'V') iv = var
         if (names(var) .eq. 'MAPFACCR') imap = var                
      end do

C     If U, V or MAPFACCR not found, return error 1
      if (iu .eq. -1 .or. iv .eq. -1 .or. imap .eq. -1) then
         print *, "Couldn't find U, V and/or MAPFACCR variables!"
         userfunc = 1
         return
      endif

      if (projection.Eq.2) then
        ds=proj_args(6)*1000.        
      else if (projection.Eq.3) then  
        ds=proj_args(5)*1000. 
      else
        print *, "Uncomprensible projection data!"
        userfunc = 1
        return
      endif

C     Compute the divergence
	do 36 il=1,maxnl
100         do ic=2,nc-1
          do ir=2,nr-1
C Calcul de la divergencia en el punt (ir,ic,il)
	outgrid(ir,ic,il)=((ingrid(ir,ic+1,il,iu)-ingrid(ir,ic-1,il,iu))/
     & (2.*ds)+(ingrid(ir-1,ic,il,iv)-
     & ingrid(ir+1,ic,il,iv))/(2.*ds))*escal
        outgrid(ir,ic,il)=outgrid(ir,ic,il)*ingrid(ir,ic,1,imap)
	enddo
	enddo
C OMPLIM ELS CONTORNS LINEALMENT
	do ir=2,nr-1
	   outgrid(ir,1,il)=2.*outgrid(ir,2,il)-outgrid(ir,3,il)
	   outgrid(ir,nc,il)=2.*outgrid(ir,nc-1,il)-outgrid(ir,nc-2,il)
	enddo
	do ic=2,nc-1
	  outgrid(1,ic,il)=2.*outgrid(2,ic,il)-outgrid(3,ic,il)
	  outgrid(nr,ic,il)=2.*outgrid(nr-1,ic,il)-outgrid(nr-2,ic,il)
	enddo
	outgrid(1,1,il)=2.*outgrid(2,2,il)-outgrid(3,3,il)
	outgrid(1,nc,il)=2.*outgrid(2,nc-1,il)-outgrid(3,nc-2,il)
       outgrid(nr,1,il)=2.*outgrid(nr-1,2,il)-outgrid(nr-2,3,il)
       outgrid(nr,nc,il)=2.*outgrid(nr-1,nc-1,il)-outgrid(nr-2,nc-2,il)
36	enddo
      USERFUNC = 0
      RETURN
      END
