% -------------------  GenSpline2d.m  --------------------------
%
% function [xc,yc,s] = GenSpline2d(x,y,cn,closed)
%
% This function computes the coefficients determining the splines
% taking into account all the possibilities: corners, closed, etc.
% It does not search for new corners or get mouse input.
%
% input: x,y(1:n) = list of coordinates of points.
%        cn = list of indices of corners.
%        closed = 0 or 1, if the curve is open or closed
%
% note that if closed==1, we assume that x(n)==x(1), y(n)==y(1)
%
% output: xc,yc(1:4;1:N) = coefficients describing the splines,
%             where N=n-1 if the curve is open and N=n if the
%             curve is closed
%         s(1:N+1) = cumulative arclengths, (same N as above).

function [xc,yc,s] = GenSpline2d(x,y,cn,closed)

if (closed==1)&(length(cn)==0) % only case ClosedSpline2d is used
  [xc,yc,s]=ClosedSpline2d(x,y);
else
  n=length(x);
  if closed==0
    if length(cn)==0
      cn=[1,n];
    else
      if cn(1)~=1
        cn=[1,cn];
      end
      if cn(length(cn))~=n
        cn=[cn,n];
      end
    end % if length(cn==0) - else -
    offset=0;
  else % closed == 1, might need to make a shifted list of points
    offset=cn(1)-1;
    if offset~=0
      x=[x(offset+1:n-1),x(1:offset),x(offset+1)];
      y=[y(offset+1:n-1),y(1:offset),y(offset+1)];
      cn=cn-offset;
    end % if offset~=0
    if cn(length(cn))~=n
      cn=[cn,n];
    end
  end % if closed==0 - else -
  % Now compute the coefficients in segments
  xc=[]; yc=[]; s=[0];
  m =length(cn);
  for i=1:m-1
    [xci,yci,si]=NSpline2d(x(cn(i):cn(i+1)),y(cn(i):cn(i+1)));
    xc=[xc,xci]; yc=[yc,yci];
    s=[s,si(2:length(si))+s(length(s))];
  end
  if (offset~=0) % closed loop, shift back to original indexing
    xc=[xc(:,n-offset:n-1),xc(:,1:n-1-offset)];
    yc=[yc(:,n-offset:n-1),yc(:,1:n-1-offset)];
    s=[s(n-offset:n-1)-s(n-offset),s(1:n-offset)+s(n)-s(n-offset)];
  end
end % the case where we don't use ClosedSpline2d