#          best_fit_parabola function
# 
# This function accepts a bmp file and an integer
#  representing a smaller matrix to fit a parabola 
#  to (starting from 0,0).
#
#
function  best_fit(comparagram_name,end_value)

##
## read in the whole image, then just consider
## the upper corner
##

C=imread(comparagram_name);

# complain if the sub matrix requested is smaller than
# the original image
Adim=size(C)
if (Adim(1) < end_value || Adim(2) < end_value)
    disp("submatrix requested is larger than original image");
    disp("... exiting ...");
    exit(1);
end
D=C(1:end_value,1:end_value);

##
## find the maximum value of each column

for i=1:end_value
  maxvalue=0;
  position=0;
  for j=1:end_value
     if D(j,i)>maxvalue
        maxvalue = D(j,i);
        position = j;
     end
  end
  max_values(i) =position;
end
#
#  fill in any values which are zero
#  which shouldn't be
#
for i=2:end_value
   if (max_values(i) == 0 && max_values(i-1) != 0)
      max_values(i) = max_values(i-1);
    end
end
## create a Vandermonde matrix for least squares
## approximation

for i = 1:end_value
   vander2(i,1)=1;
   vander2(i,2)=i;
   vander2(i,3)= i*i;
end
vander=vander2(1:end_value,1:3);
##
## compute the least squares approximation
##
bestfit = (inv(vander'*vander)*vander');
bestfit=bestfit*max_values
for i= 1:255
    white_pixel=i*i*bestfit(3)+i*bestfit(2)+bestfit(1)+1;
    if (white_pixel >=1 ) 
       C(white_pixel,i)=256;
    end
end
##
## Show the result against the original image
##
imshow(C);
