module ols
use qrgivens
implicit none
contains
function lsfit(m,f,x,y,dy,s) result(c)
real*4,intent(in)::x(:),y(:),dy(:)
interface
function f(i,z)
integer,intent(in)::i
real*4,intent(in)::z
real*4::f
end function f
end interface
integer,intent(in)::m
integer::n,i,j
real*4,intent(out)::s(:,:)
real*4::c(m),a(size(x),m),b(size(x)),ai(m,m)
n=size(x)
do i=1,n
	b(i)=y(i)/dy(i)
	do j=1,m
		a(i,j)=f(j,x(i))/dy(i)
	end do
end do
call qrdec(a)
c=qrsolve(a,b)
ai=qrinv(a)
s=matmul(ai,transpose(ai))
end function lsfit
end module ols
