C TD.f
C TD.f
C
C VIS-5D analysis function to compute Dew point Temperature (in C)

      INTEGER FUNCTION USERFUNC( OUTGRID, OUTNL, OUTLOWLEV,
     *                           INGRID, NR, NC, NL, LOWLEV, MAXNL,
     *                           NVARS, NAMES,
     *                           DATE, TIME,
     *                           PROJECTION, PROJ_ARGS,
     *                           VERTICAL, VERT_ARGS )
c	implicit none
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
      integer it,ihum
      real ews

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

C     Find the T and RH variables
      it = -1
      ihum = -1
      do var=1,nvars
         if (names(var) .eq. 'T') it = var
         if (names(var) .eq. 'RH') ihum = var
      end do

C     If T,or RH not found, return error 1
      if (it .eq. -1 .or. ihum .eq. -1) then
         print *, "Couldn't find T and/or RH variables!"
         userfunc = 1
         return
      endif
		DO 5770 J=1,nc
		DO 5770 I=1,nr

c	Entran T,RH
		DO 1101 K=1,outnl
	EWS=VAPFW(ingrid(i,j,k,it))
	outgrid(i,j,k)=DPTOF(EWS*ingrid(i,j,k,ihum)/100.)
 1101		CONTINUE
5770 	continue
      USERFUNC = 0
      RETURN
      END



c ===========================================================================
C	ALGORITMO PARA CALCULAR LA PRESION DE VAPOR SATURANTE
C	RESPECTO AL AGUA EN hPa.
c	ENTRADA TEMPERATURA EN C.

	FUNCTION VAPFW(T)

	X=T
	IF(100.-X)3,4,4

3	X=X-273.16

C	AJUSTE DE LA CURVA ENTRE -50 < T < 100
4	POL=.99999683E-0+X*(-.90826951E-2+X*(.78736169E-4+
     1	X*(-.61117958E-6+X*(.43884187E-8+X*(-.29883885E-10+
     2	X*(.21874425E-12+X*(-.17892321E-14+X*(.11112018E-16+
     3	X*(-.30994571E-19)))))))))
	POL=POL*POL
	POL=POL*POL
	VAPFW=6.1078/(POL*POL)
	RETURN
	END
c ===========================================================================


c ===========================================================================
C	ALGORITMO PARA INVERTIR LA FORMULA DE TETENS
C	CALCULA LA TEMPERATURA EN GRADOS C DADA LA PRESION DE VAPOR
C	SATURANTE EN hPa

	FUNCTION DPTOF(EW)

	TOL=.0001
	IF (EW-.21382876E-9)20,20,30

20	DPTOF=-10000.
	RETURN

30	IF (1013.-EW)20,100,100

100	X=ALOG(EW/6.1078)
	BOT=17.269388-X
	DPTOF=(273.3*X)/BOT
	BOT=BOT*EW
200	EDP=VAPFW(DPTOF)
	DTDE=(DPTOF+237.7)/BOT
	DELT=DTDE*(EW-EDP)
	DPTOF=DPTOF+DELT

	IF(ABS(DELT)-TOL)300,300,200

300	DPTOF=DPTOF-TOL
	RETURN
	END
c ===========================================================================

