*------------- Telecommunications & Signal Processing Lab --------------
*                          McGill University
*
*
* Module:
*     REAL FUNCTION GDLFIR (F, H, N)
*
*
* Purpose:
*     Find the group delay for an FIR filter
*
*
* Description:
*     The group delay is calculated for the equivalent non-causal filer
*     with reference point at the mid-point of the filter.  The delay
*     to the mid-point is added to this figure.  The group delay in
*     seconds at frequency f for a response with sampling frequency Fs
*     can be calculated as
*
*       T = GDLFIR(f/Fs,H,N) / Fs  .
*
*     If the given frequency corresponds to a zero of the response, a
*     warning message is printed and the group delay is set to 1E20.
*
*
* Parameters:
* R <-  GDLFIR - Group delay in samples
*
* R ->  F      - Normalized frequency (normally in the range 0 to 0.5)
* R ->  H      - Array of impulse response coefficients
* I ->  N      - Number of impulse response coefficients
*
*
* Author / revision:
*     P. Kabal
*     $Revision: 1.5 $  $Date: 1995/03/08 15:21:11 $
*
*
*-----------------------------------------------------------------------

      REAL FUNCTION GDLFIR (F, H, N)


      REAL PI2
      PARAMETER (PI2=6.283 185 307)

      INTEGER N
      INTEGER I

      REAL F
      REAL HE,HO,AI,COSWI,SINWI,ANUM,ADEN
      REAL H(-((N-1)/2):*)

      DOUBLE PRECISION DSUMHR,DSUMHI,DSUMDR,DSUMDI


      IF (MOD(N,2).EQ.0) THEN
        DSUMHR=0.
      ELSE
        DSUMHR=H(0)
      END IF
      DSUMHI=0.
      DSUMDR=0.
      DSUMDI=0.

* Calculate the terms for the group delay computation in terms
* of the non-causal filter with reference point at the mid-point
* of the filter
*  DSUMHR - Re[H(f)]
*  DSUMHI - Im[H(f)]
*  DSUMDR - Re[H'(f)]
*  DSUMDI - Im[H'(f)]
      DO 100 I=1,N/2
        IF (MOD(N,2).EQ.0) THEN
          HE=H(I)+H(-I+1)
          HO=H(I)-H(-I+1)
          AI=I-0.5
        ELSE
          HE=H(I)+H(-I)
          HO=H(I)-H(-I)
          AI=I
        END IF
        COSWI=COS(PI2*F*AI)
        SINWI=SIN(PI2*F*AI)
        DSUMHR=DSUMHR+DPROD(HE,COSWI)
        DSUMHI=DSUMHI-DPROD(HO,SINWI)
        DSUMDR=DSUMDR-DPROD(AI*HE,SINWI)
        DSUMDI=DSUMDI-DPROD(AI*HO,COSWI)
 100  CONTINUE

* Calculate the group delay
      ANUM=DSUMDR*DSUMHI-DSUMDI*DSUMHR
      ADEN=DSUMHR**2+DSUMHI**2
      IF (ADEN.EQ.0.0) THEN
        CALL WARN('GDLFIR - Undefined delay')
        GDLFIR=1E20
      ELSE
        GDLFIR=0.5*(N-1)+ANUM/ADEN
      END IF


      RETURN

      END
