C TEMAD.f
C
C VIS-5D analysis function to compute Temperature advection 
C (in 1E-5 deg 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 it,iu,iv
      real xincx,xincy,gradx,grady,Pi,Rt,escal,ds
      PARAMETER(Pi=3.141596,Rt=6371227.,escal=1.e5)   

	print*,'Reescalat en 1.e5'
C     Specify number of levels in OUTGRID
      OUTNL = MAXNL
      OUTLOWLEV = 0
      
C   Find the U, V, T, and MAPFACCR variables
      it = -1
      iu = -1
      iv = -1
      imap = -1      
      do var=1,nvars
         if (NAMES(var).eq."T") it = var
         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,T or MAPFACCR not found, return error 1
      if (it.eq.-1 .or. iu.eq.-1 .or. iv.eq.-1
     $   .or. imap.eq.-1) then
         print *, "Couldn't find T, U, V or MAPFACCR vars!"
         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 3-D Temperature Advection
	xincy=2.*ds
      do il=1,maxnl
         do ic=2,nc-1
            do ir=2,nr-1
        xincx=2.*ds
  	gradx=(ingrid(ir,ic+1,il,it)-ingrid(ir,ic-1,il,it))/xincx
        gradx=gradx*ingrid(ir,ic,1,imap)	
	grady=(ingrid(ir-1,ic,il,it)-ingrid(ir+1,ic,il,it))/xincy
        grady=grady*ingrid(ir,ic,1,imap)	
        outgrid(ir,ic,il) =-(ingrid(ir,ic,il,iu)*gradx+
     &  ingrid(ir,ic,il,iv)*grady)*escal
            end do
         end do


        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(nr,nc,il)=2.*outgrid(nr-1,nc-1,il)-outgrid(nr-2,nc-2,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)
      end do

      USERFUNC = 0
      RETURN
      END
