% A new method proposed, assume we can use the comparagram
% to approximate an underlying function with a series
% of cubic splines.
clear W
f=0:255;
%g=sqrt(2)*f;
clear g
%% here's the justification for the following line
%% (formula for the comparagram)
% if we have the function f(x) = sqrt(x), then the
% comparametric plot will f(x) against f(2x), which
% will consequently be sqrt(x) against sqrt(2x)
% == sqrt(x) against sqrt(2)sqrt(x)
% == 1 against sqrt(2)
% which is simply a plot of f(x)= sqrt(2) * x
coeff=[sqrt(2) 0];

% again, the assumption that f(1) = 1 is made, the following
% code finds how many points we will use and therefore how many
% splines we will get.
num_of_unrolled_pts = 1; %we know f(1)=1
x_val=1; flat_spot_detect = 0;% detect a flat spot of the comparagram
while (polyval(coeff,x_val)<256)
   x_val_new=polyval(coeff,x_val);
   if (x_val_new == x_val)
      flat_spot_detect = 1;
      disp('the comparagram contains a saturation point or a flat region');
      disp('the maximum value attained was');
      disp(x_val);
   else
      x_val=x_val_new;
      num_of_unrolled_pts = num_of_unrolled_pts+1;
   end
end
num_of_unrolled_pts
% do some unrolling

% this will start the unrolling at f=1
% where to start the unrolling from along the f-axis

% this method will attempt to build co-orinate pairs
x(1) = 0; y(1) = 0; % want the spline to pass through 0
x(2) = 1; y(2) = 1; % the initial assumption i.e. f(q_1)=1
for i=3:num_of_unrolled_pts+2
   x(i) = 2* x(i-1);
   y(i) = polyval(coeff,y(i-1));
end

%generate the third component for the spline function
xspline = 0:2:100;
yspline = spline(x,y,xspline);

%also generate the true solution
xreal = xspline;
yreal = sqrt(xspline);
system("rm plot_found_sqrt_function.ps");
title("An Example of a Spline Approximation to f(x) from a Comparagram");
xlabel("x");
ylabel("sqrt(x)");
grid("on");
gset terminal postscript 22 
gset output "plot_found_sqrt_function.ps"
%plot the comparasolved function against the real function
plot(xspline,yspline,'-;spline approximation to sqrt(x);',xreal,yreal,'@;actual sqrt(x);');
