function test=inpoly(x,p)

% INPOLY      Test whether points lie in a polygon.
%
%             Example: load as.dat
%                      inpoly([22 -31; 23 -32;0 0],as)
%
%             INPOLY(X,P) tests whether points in 2 column matrix X lie
%             in the polygon defined by P (again defined by 2 columns).
%
%             Christian C. Beardah 1996

[r,c]=size(x);

test=zeros(r,1);

for i=1:(length(p)-1),
    
  m=(p(i+1,2)-p(i,2))/(p(i+1,1)-p(i,1)+eps);
  c=p(i,2)-m*p(i,1);

  testx=(x(:,1)>min(p(i:(i+1),1)) & x(:,1) < max(p(i:(i+1),1)));
  testy=(x(:,2) < m*x(:,1)+c);
  test=test+(testx & testy);

end;

test=(rem(test,2)==1);