      real*8 function fchisq(y,sigmay,npts,nfree,mode,yfit,maxp)
      implicit undefined(a-z)
      integer*4 maxp,nfree,mode
      real*8 y(maxp),sigmay(maxp),yfit(maxp)
      real*8 weight,chisq
      integer*4 npts,i
      chisq=0.
      if(nfree.le.0)then
       fchisq=0.
       goto 40
      endif
c
c     Accumulate chi square
c
      do 30 i=1,npts
      if(mode.eq.0)goto 27
      if(mode.gt.0)goto 29
      if(y(i).lt.0)goto 25
      if(y(i).eq.0)goto 27
      weight=1./y(i)
      goto 30
   25 weight=1./(-y(i))
      goto 30
   27 weight=1.
      goto 30
   29 weight=1./sigmay(i)**2
   30 chisq=chisq+weight*(y(i)-yfit(i))**2
c
c     divide by number of degrees of freedom
c
      chisq=chisq/nfree
      fchisq=chisq
   40 return
      end

