% process the curves
onProcess;

% for each point in curve1 determine (quite possibly noninteger) matching curve2 coordinates
m = size(curve1, 1);
n = size(curve2, 1);
match = zeros(m, 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:m-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;
    if flPt == n
        flPtNext = n;
    else
        flPtNext = flPt+1;
    end
	match(i+2,1) = (1 - rem)*curve2(flPt, 1) + rem*curve2(flPtNext, 1);
	match(i+2,2) = (1 - rem)*curve2(flPt, 2) + rem*curve2(flPtNext, 2);
end

% generate average curve
avgCurve = zeros(m, 2);
for i = 1:m,
    avgCurve(i,:) = 0.5*curve1(i,:) + 0.5*match(i,:);
end

% display it
figure;
set(gcf, 'Name', 'Average of curve1 and curve2');
plot( ...
  avgCurve(1:end,1), ...
  avgCurve(1:end,2), ...
  'Color','b', ...
  'EraseMode','none', ...
  'MarkerSize', 6, ...
  'Marker', 'none');    
%axes;
axis off;
axis tight;
axis equal;
