c	program main
c	call gset							!  enter graphic mode
c	call sfit
c	call aset							!  return to alpha mode
c	end	
c	-----------------------------------------------------------------------
	subroutine sfit
c
c	...fit a straight line to data
c
c	(C) Copyright 1988, 1989 by Jim Farrell      All Rights Reserved.
c
	parameter (n=100)
	real x(n),y(n)
c
	fn(x)=30.0+2.0/3.0*x				!  linear function
c
	ikr=1.0
	xmax=real(n)/2.0
	xmin=-xmax
	ymin=fn(xmin)
	ymax=fn(xmax)
	dx=(xmax-xmin)/(n-1)
	dy=(ymax-ymin)/5.0
	call putstr(10,20,' DEMONSTRATION MULTIPLE PLOT OVERLAYS')
	call putstr(12,20,'       FOR A LEAST SQUARES FIT')
	call pause('WHEN READY ')		!  display message and pause
	call gcls
	call mulplt0(xmin,ymin-dy,xmax,ymax+dy)	!  set max/mins
	do 200 i=1,n						!  compute line from function
		x(i)=xmin+dx*real(i-1)
		y(i)=fn(x(i))
200	continue
	call mulplt(x,y,n,4)				!  plot as connected lines
	call pause('REVIEW PLOT OF PURE LINE')
	do 300 i=1,n						!  corrupt data with noise & bias
		x(i)=xmin+(xmax-xmin)*rand(ikr)
		y(i)=fn(x(i))+dy*sign(rand(ikr),rand(ikr)-0.3)
300	continue
	call mulplt(x,y,n,0)				!  plot as points
	call pause('REVIEW PLOT OF CORRUPTED DATA')
	call fits(x,y,n,a,b)				!  fit slope & intercept
	do 400 i=1,n						!  compute line based on fit
		x(i)=xmin+dx*real(i-1)
		y(i)=a+b*x(i)
400	continue
	call mulplt(x,y,n,4)				!  plot as connected lines
	call pause('REVIEW PLOT OF COMPUTED LINE')
	return
	end
c	-----------------------------------------------------------------------
	subroutine fits(x,y,ndata,a,b)
c
c	...fit a straight line to data (i.e. determine slope and intercept)
c
	real x(*),y(*)
c
	sx=0.0
	sy=0.0
	do 130 i=1,ndata
		sx=sx+x(i)
		sy=sy+y(i)
130	continue
	sxoss=sx/real(ndata)
	st2=0.0
	b=0.0
	do 140 i=1,ndata
		t=x(i)-sxoss
		st2=st2+t**2
		b=b+t*y(i)
140	continue
	b=b/st2
	ss=real(ndata)
	a=(sy-sx*b)/ss
	return
	end
