*------------- Telecommunications & Signal Processing Lab --------------
*                          McGill University
*
*
* Module:
*     REAL FUNCTION PHSFIR (F, H, N)
*
*
* Purpose:
*     Find the phase response for an FIR filter
*
*
* Description:
*     The phase response is calculated for the equivalent non-causal
*     filter with reference point at the mid-point of the filter.
*     The phase corresponding to the delay up to the mid-point of
*     the filter is added to this figure.  If the given frequency
*     corresponds to a zero of the response, a warning message is
*     printed and the phase is set to zero.
*
*
* Parameters:
* R <-  PHSFIR - Phase in radians.  This value is in the range -Pi to
*                Pi.
*
* 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:37 $
*
*
*-----------------------------------------------------------------------

      REAL FUNCTION PHSFIR (F, H, N)


      REAL PI,PI2
      PARAMETER (PI=3.141 592 654, PI2=6.283 185 307)

      INTEGER N
      INTEGER I

      REAL F
      REAL HE,HO,RSUMHI,RSUMHR
      REAL H(-((N-1)/2):*)

      DOUBLE PRECISION DSUMHR,DSUMHI


      DSUMHI=0.

* Calculate the real and imaginary parts of the frequency response
* of the non-causal filter with reference point at the mid-point
* of the filter
*  DSUMHR - Re[H(f)]
*  DSUMHI - Im[H(f)]
      IF (MOD(N,2).EQ.0) THEN

        DSUMHR=0.
        DO 100 I=1,N/2
          DSUMHR=DSUMHR+DPROD(H(I)+H(-I+1),COS(PI2*F*(I-0.5)))
          DSUMHI=DSUMHI-DPROD(H(I)-H(-I+1),SIN(PI2*F*(I-0.5)))
 100    CONTINUE

      ELSE

        DSUMHR=H(0)
        DO 200 I=1,(N-1)/2
          HE=H(I)+H(-I)
          HO=H(I)-H(-I)
          DSUMHR=DSUMHR+DPROD(H(I)+H(-I),COS(PI2*F*I))
          DSUMHI=DSUMHI-DPROD(H(I)-H(-I),SIN(PI2*F*I))
 200    CONTINUE

      END IF

* Calculate the phase
      RSUMHI=DSUMHI
      RSUMHR=DSUMHR
      IF (RSUMHR.EQ.0.0 .AND. RSUMHI.EQ.0.0) THEN
        CALL WARN('PHSFIR - Undefined phase')
        PHSFIR=0.0
      ELSE
        PHSFIR=-PI*(N-1)*F+ATAN2(RSUMHI,RSUMHR)
        IF (PHSFIR.GE.0) THEN
          PHSFIR=MOD(PHSFIR+PI,PI2)-PI
        ELSE
          PHSFIR=MOD(PHSFIR-PI,PI2)+PI
        END IF
      END IF


      RETURN

      END
