% for each point in curve1 determine (quite possibly noninteger) matching curve2 coordinates
n = size(curve1, 1);
match = zeros(n, 2);
% endpoints match
match(1,:) = curve2(1,:);
match(end,:) = curve2(end,:);
p = size(c, 1);
% p is the location of first occurence of i in left col of c()
% coord vector at that location
firstOccur = c(p,:);    
% corresponding s value (+1 endpoint compensation)
s_val = firstOccur(2) + 1; 
% compute coords of matching point at curve2(first_s_val) by interpolating
flPt = floor(s_val);
rem = s_val - flPt;
match(2,1) = (1 - rem)*curve2(flPt, 1) + rem*curve2(flPt+1, 1);
match(2,2) = (1 - rem)*curve2(flPt, 2) + rem*curve2(flPt+1, 2);
for i = 1:n-2,
    % linearly search for the last occurence of coordinate 
    % i in t of c() = (t, s), t - curve 1 coord, s - curve 2 coord
    % continue searching for second occurence from last value of p
    while (p > 1) & (c(p, 1) < i+1),
        p=p-1;
    end
	% corresponding s value
	s_val = c(p,2) + 1; 
    
    % compute coords of matching point at curve2(last_s_val) by interpolating
	flPt = floor(s_val);
	rem = s_val - flPt;
	match(i+2,1) = (1 - rem)*curve2(flPt, 1) + rem*curve2(flPt+1, 1);
	match(i+2,2) = (1 - rem)*curve2(flPt, 2) + rem*curve2(flPt+1, 2);
end

% generate morph frames
% move each point of curve1 along a line towards corresponding point in curve 2
% first determine timesteps for each line
numFrames = 20;
tstep = zeros(n,1);
direction = zeros(n,2);
for i = 1:n,
    diffVec = match(i,:) - curve1(i,:);
    diffVecLen = norm(diffVec);
    direction(i,:) = diffVec/diffVecLen;
    tstep(i,:) = diffVecLen/numFrames;
end
% move a point according to its corrseponding timestep
morphFrame = zeros(numFrames, n, 2);
morphFrame(1,:,:) = curve1;
% display first frame - curve1 itself
figure;
axes;
axis off;
axis tight;
axis equal;
% draw frame on new figure 
line( ...
  morphFrame(1,1:end,1), ...
  morphFrame(1,1:end,2), ...
  'Color','b', ...
  'EraseMode','none', ...
  'MarkerSize', 6, ...
  'Marker', 'none');    
for frame = 2:numFrames,
    for i = 1:n,
        morphFrame(frame,i,:) = curve1(i,:) + tstep(i)*frame*direction(i,:);
    end
    % display frame
    figure;
	axes;
    axis off;
    axis tight;
    axis equal;
	% draw frame on new figure 
	line( ...
      morphFrame(frame,1:end,1), ...
      morphFrame(frame,1:end,2), ...
      'Color','b', ...
      'EraseMode','none', ...
      'MarkerSize', 6, ...
      'Marker', 'none');    
  
    epsfilename = sprintf('three_to_two_frame%d.eps', frame);
    print('-depsc', epsfilename);
end


