      program linfit

      implicit none

      integer*4 jds(100)
      real*4 x(100), y(100), dy(100), w(100)
      real*4 xx, yy, dyy
      integer*4 i, ids, npts
      real*4 Rise, Run, RR
      real*4 S0, Sx, Sy, Sxx, Syy, Sxy
      real*4 p0, p1
      character*24 fname

      open (7, file='ANSWER')
      rewind (7)
      write (7,*) ' '
      write (7,*) '      LINEAR MINIMUM-CHISQUARED FITTING'
      write (7,*) '      ================================='
      write (*,*) ' '
      write (*,*) '      LINEAR MINIMUM-CHISQUARED FITTING'
      write (*,*) '      ================================='
      write (*,*) ' '

      write (*,1111) 
 1111 format('Enter the name of the file containing the data: ',$)
      read (*,*) fname

      open (2, file=fname)

      write (7,*) ' '
      write (7,*) 'READING IN FILE ',fname,':'
      write (7,*) ' '
      write (*,*) ' '
      write (*,*) 'READING IN FILE ',fname,':'
      write (*,*) ' '

      do i=1,10
         read (2,*,end=1000) ids, xx, yy, dyy
         write (7,*) ids, xx, yy, dyy
         write (*,*) ids, xx, yy, dyy
         jds(i) = ids
         x(i) = xx
         y(i) = yy
         dy(i) = dyy
         w(i) = 1/(dyy*dyy)
      end do

 1000 npts = i - 1
      write (7,*) ' '
      write (7,*) 'Read ',npts,' rows of data.'
      write (7,*) ' '
      write (*,*) ' '
      write (*,*) 'Read ',npts,' rows of data.'
      write (*,*) ' '

      Rise = y(npts) - y(1)
      Run = x(npts) - x(1)
      RR = Rise/Run
C      write (*,*) 'Rise/Run = ',RR

      S0 = 0
      Sx = 0
      Sy = 0
      Sxx = 0
      Syy = 0
      Sxy = 0

      do i=1,npts
	S0 = S0 + w(i)
	Sx = Sx + w(i)*x(i)
	Sy = Sy + w(i)*y(i)
	Sxx = Sxx + w(i)*x(i)**2
	Syy = Syy + w(i)*y(i)**2
	Sxy = Sxy + w(i)*x(i)*y(i)
      end do

C      S0 = S0/npts
C      Sx = Sx/npts
C      Sy = Sy/npts
C      Sxx = Sxx/npts
C      Syy = Syy/npts
C      Sxy = Sxy/npts

      p0 = (Sy*Sxx - Sx*Sxy)/(S0*Sxx - Sx*Sx)
      p1 = (S0*Sxy - Sx*Sy)/(S0*Sxx - Sx*Sx)

C      write (*,*) 'S0,Sx,Sy,Sxx,Syy,Sxy = ',S0,Sx,Sy,Sxx,Syy,Sxy

      write (*,*) ' '
      write (*,*) '      BEST FIT:'
      write (*,*) ' '
      write (*,*) 'Intercept p0 = ',p0
      write (*,*) '   Slope p1 = ',p1
      write (*,*) '(Compare Rise/Run = ',RR,')'
      write (*,*) ' '

      write (7,*) ' '
      write (7,*) '      BEST FIT:'
      write (7,*) ' '
      write (7,*) 'Intercept p0 = ',p0
      write (7,*) '    Slope p1 = ',p1
      write (7,*) '(Compare Rise/Run = ',RR,')'
      write (7,*) ' '

      close (7)

      stop
      end
