      FUNCTION CHISQD(P, N)

c*********************************************************************72

      DIMENSION C(21), A(19)
      DATA C(1)/1.565326E-3/, C(2)/1.060438E-3/,
     &  C(3)/-6.950356E-3/, C(4)/-1.323293E-2/,
     &  C(5)/2.277679E-2/, C(6)/-8.986007E-3/,
     &  C(7)/-1.513904E-2/, C(8)/2.530010E-3/,
     &  C(9)/-1.450117E-3/, C(10)/5.169654E-3/,
     &  C(11)/-1.153761E-2/, C(12)/1.128186E-2/,
     &  C(13)/2.607083E-2/, C(14)/-0.2237368/,
     &  C(15)/9.780499E-5/, C(16)/-8.426812E-4/,
     &  C(17)/3.125580E-3/, C(18)/-8.553069E-3/,
     &  C(19)/1.348028E-4/, C(20)/0.4713941/, C(21)/1.0000886/
      DATA A(1)/1.264616E-2/, A(2)/-1.425296E-2/,
     &  A(3)/1.400483E-2/, A(4)/-5.886090E-3/,
     &  A(5)/-1.091214E-2/, A(6)/-2.304527E-2/,
     &  A(7)/3.135411E-3/, A(8)/-2.728484E-4/,
     &  A(9)/-9.699681E-3/, A(10)/1.316872E-2/,
     &  A(11)/2.618914E-2/, A(12)/-0.2222222/,
     &  A(13)/5.406674E-5/, A(14)/3.483789E-5/,
     &  A(15)/-7.274761E-4/, A(16)/3.292181E-3/,
     &  A(17)/-8.729713E-3/, A(18)/0.4714045/, A(19)/1./

      if ( n < 2 ) then
        CHISQD = GAUSSD(.5*P)
        CHISQD = CHISQD*CHISQD
        RETURN
      else if ( n == 2 ) then
        CHISQD = -2. * ALOG(P)
        RETURN
      else
        F = N
        F1 = 1. / F
        T = GAUSSD(1.-P)
        F2 = SQRT(F1) * T
        IF ( N < (2+INT(4.*ABS(T)))) then
          CHISQD=(((((((C(1)*F2+C(2))*F2+C(3))*F2+C(4))*F2
     &      +C(5))*F2+C(6))*F2+C(7))*F1+((((((C(8)+C(9)*F2)*F2
     &      +C(10))*F2+C(11))*F2+C(12))*F2+C(13))*F2+C(14)))*F1 +
     &      (((((C(15)*F2+C(16))*F2+C(17))*F2+C(18))*F2
     &      +C(19))*F2+C(20))*F2+C(21)
        else
          CHISQD = (((A(1)+A(2)*F2)*F1+(((A(3)+A(4)*F2)*F2
     &      +A(5))*F2+A(6)))*F1+(((((A(7)+A(8)*F2)*F2+A(9))*F2
     &      +A(10))*F2+A(11))*F2+A(12)))*F1 + (((((A(13)*F2
     &      +A(14))*F2+A(15))*F2+A(16))*F2+A(17))*F2*F2
     &      +A(18))*F2+A(19)
        end if
        CHISQD = CHISQD*CHISQD*CHISQD*F
      end if

      RETURN
      END
