  function [u,v] = PolygonCrossings(x,y)
% x and y are n-vectors that encode the vertices of a ploygon.
% If k<n, the k-th edge has endpoints (x(k),y(k)) and (x(k+1),y(k+1))
% If k=1, the k-th edge has endpoints (x(k),y(k)) and (x(1),y(1))
% u and v are length-m column vectors that house the crossing points
% (u(1),v(1)),...,(u(m),v(m)). Note that if there are no crossing points,
% then u and v are empty vectors.

n = length(x);
u = [];
v = [];
for k=1:n-2
    % Identify the intersection points associated with the kth edge.
    for i=k+2:n
        % Compare edge k with edge i, but remember two
        % things. (a) The n-th edge has (x(1),y(1)) for its "destination" 
        % endpoint and (b)the first edge is not checked against the n-th
        % edge.
        if i<n
            a = [x(k) x(k+1) x(i) x(i+1)];
            b = [y(k) y(k+1) y(i) y(i+1)];
        elseif k>1
            a = [x(k) x(k+1) x(i) x(1)];
            b = [y(k) y(k+1) y(i) y(1)];
        end
        z = Intersect(a,b);
        if ~isempty(z)
            % Intersection point found...
            u = [u;z(1)];
            v = [v;z(2)];
        end
    end
end
        