function [xy0, xy1] = fitLineSegmentToContourChain(ps)
% This function takes as input a chain of contour points specified as a
% 2 x K matrix 'ps', and returns the endpoints 'xy0' and 'xy1' of a line
% segment fitted through the points in the chain.

    % Fit a straight line through the points, by computing the directions
    % of maximum variance using SVD:
        % Compute the mean of the set 'ps':
        ps_bar = mean(ps, 2);
        
        % Shift the origin of the points to 'ps_bar':
        ps_mean_0 = ps - repmat(ps_bar, 1, size(ps,2));
        
        % Find the direction of largest variance using SVD:
        [U,S,V] = svd(ps_mean_0');
    
    % This is the direction of the fitting line:
    d = V(:,1);
    
    % It is a known propoerty that the line with direction 'd' that
    % will achieve the least cumulative error for all points in 'ps' is
    % the one going through 'ps_bar'.
    
    % Find the endpoints of the line segment, by projecting all points in
    % 'ps' onto the line, and retaining those two that project furthest
    % away on the line:
    lambdas = d' * ps_mean_0;
    l0 = min(lambdas);
    l1 = max(lambdas);
    xy0 = ps_bar + l0 * d;
    xy1 = ps_bar + l1 * d;

%     figure(1111); plot(ps(1,:), ps(2,:), 'or'); hold on;
%     line([xy0(1), xy1(1)], [xy0(2), xy1(2)]);
%     plot(xy0(1), xy0(2), 'ob'); plot(xy1(1), xy1(2), 'ob');
end
