      subroutine fit_l(ndat,x,y,sgy,a,sga,chi2,q,cov)
c
c  bernd berg, november 2 2000.
c  given is a set of ndat points x(i), y(i) with standard deviations
c  sgy(i). minimizing chi^2 they are fitted to a straight line.
c
c  returned are a(1), a(2) and their error bars sga(1), sga(2).
c  for n.ge.3: also the chi-square chi2, and the goodnes of fit q.
 
      include '../../libs/fortran/implicit.sta'
      include '../../libs/fortran/constants.par'
      dimension a(2),sga(2),x(ndat),y(ndat),sgy(ndat)
      sx=zero
      sy=zero
      stt=zero
      a(2)=zero
      s=zero
      do i=1,ndat
        wt=one/sgy(i)**2
        s=s+wt
        sx=sx+x(i)*wt
        sy=sy+y(i)*wt
      end do
      sxos=sx/s
      do i=1,ndat
        t=(x(i)-sxos)/sgy(i)
        stt=stt+t*t
        a(2)=a(2)+t*y(i)/sgy(i)
      end do
      a(2)=a(2)/stt
      a(1)=(sy-sx*a(2))/s
      sga(1)=sqrt((one+sx*sx/(s*stt))/s)
      sga(2)=sqrt(one/stt)
      cov=-sx/(s*stt)
      chi2=zero
      do i=1,ndat
        chi2=chi2+((y(i)-a(1)-a(2)*x(i))/sgy(i))**2
      end do
      if (ndat.gt.2) q=one-gamma_p(half*(ndat-2),half*chi2)
      return
      end
