function out = pt_in_poly(x,poly);

%PT_IN_POLY sums angles to determine whether x is in poly

%Written by T.E.Smith, 1/25/04

%INPUTS:      x = test point, x = [x1,x2]
%          poly = polygon of points [poly(1,:) = poly(end,:)]

%GOOD EXAMPLE:  x = [1 -2];
%               poly = [-1 -1
%                        1  0
%                       -1  1
%                        0  2
%                        2  1
%                        2 -1
%                        0 -2
%                       -1 -1];

n = size(poly,1);

u = ones(n,1);

YY = poly - u*x;

Z = YY(:,1) + i*YY(:,2);

theta = angle(Z);

M = [theta(2:end),theta(1:end-1)];

I1 = (M(:,1).*M(:,2) < 0); %find opposite sign cases

I2 = (abs(M(:,1)) + abs(M(:,2)) > pi); %find tot abs > pi

I = I1.*I2; %Combine to get "bad" cases

Diff = M(:,1) - M(:,2);

u1 = ones(n-1,1);

R = (u1 - I).*Diff + I.*(Diff -2*pi*sign(Diff));

tot = sum(R);

if abs(tot) > 1
    
    out = 1;
    
else
    
    out = 0;
    
end







