% -----------------------  Param2dSpline.m  ---------------------
%
% function [n,xout,yout,s,xc,yc,newcn,errorbound] = Param2dSpline(...
%   mouse,x,y,func,closed,cn,corners);
%
% inputs: mouse = 0 if no mouse input, 
%               = 1 if mouse input:
%                   left click   = non-corner point on spline
%                   right click = corner point on spline
%                   any other (keyboard) click  = end of mouse input
%           
%         x,y : lists of coordinates of points, ignored if mouse==1
%         func : name of a function for errorbound check, ignored if
%                func==''
%         closed = 1 if curve is closed, 0 otherwise.
%         cn = list of indices of preidentified corners, ignored if 
%              mouse==1
%         corners = 0 if no automatic corner detection required, 
%                   otherwise its the threshhold angle for corners.
%
% outputs: n = total number of distinct points
%          xout,yout : lists of coordinates of points
%          s = list of arclength parameter values at points
%          xc,yc = coefficients defining x,y respectively as a spline
%                  as described in programming assignment
%                  see NaturalSpline.m for more explanation 
%                  (these are 4-by-(n-1) matrices if closed = 0, or
%                             4-by-n     matrices if closed = 1)
%          newcn = list of all corners in order, detected as well as
%                  input corners
%          errorbound = max(abs(func)) at 1000 points on the curve
%

function [n,xout,yout,s,xc,yc,newcn,errorbound] = Param2dSpline(...
  mouse,x,y,func,closed,cn,corners);

% error checks:
if mouse==0
  if length(x)~=length(y)
    display('Error: x and y have different lengths'); return
  end
  if length(x)<2
    display('Nothing to do here: need at least two points');
    return
  end
  if (any(cn<1))|(any(cn>length(x)))
    display('Bad corner indices');
    return;
  end
end

[xout,yout,newcn]=PreparePoints(mouse,x,y,closed,cn,corners);
if closed==0
  n=length(xout);
else 
  n=length(xout)-1;
end;
[xc,yc,s] = GenSpline2d(xout,yout,newcn,closed);
clf;
Plot2dSpline(xc,yc,s,1000);
hold on;
if (length(newcn)>0)
   for j=1:length(xout), 
      if (min(abs(newcn - j)) > 0),
         plot(xout(j),yout(j),'ro')
      end
   end
else
   plot(xout,yout,'ro')
end
plot(xout(newcn),yout(newcn),'b+');
plot(xout([1,length(xout)]),yout([1,length(yout)]),'m*');
% plot(xout,yout,'bo',xout(newcn),yout(newcn),'gx',...
%   xout([1,length(xout)]),yout([1,length(yout)]),'m*');
if mouse==1
  axis([-1 1 -1 1]);
end
if length(func)>0
  errorbound=MaxAbsFSpline(func,xc,yc,s,1000);
end