function [polytype, passi, passe, xint, yint, jint, kint, kfrac] = polyfilter(lat,long)
%
%     This script finds whether storm tracks cross line segments given in
%     'poly.in'. Passe= 1 if track meets the criterion, 0 if it does not. Also
%     finds whether each point on a track lies entirely within a set of line 
%     segments if they constitute a closed polygon. If so, passi is set to 
%     unity, otherwise to zero. (Note that passi = 1 by default if line 
%     segments are not a closed polygon. Also note that passi is a 2-D matrix
%     and that passe is a 1-D vector.)
%
%     Polytype is 'closed' for closed polygons, 'open' otherwise.
%
%     The quantities xint and yint constitute the intersection points,
%     along the line segment numbered jint and the kint'th point along the
%     track. kfrac is the fraction of the distance between track points i
%     and i+1 that the intersection occurs. 
%
%     Note that passe is a vector of length n, where n is the number of
%     tracks, and the other quantities are matrices of dimension
%     (n,maxtimes), where maxtimes is the specified upper limit on the
%     number of times a particular track may intersect the set of line
%     segments. 
%
% Copyright 2012 WindRiskTech L.L.C.
% Last modified September, 2012
%-------------------------------------------------------------------------
[n,m]=size(lat);
%
% Read in line segments from file 'poly'in'
%
a=load('poly.in');
xa=a(:,1);
ya=a(:,2);
xb=a(:,3);
yb=a(:,4);
xn=[xa;xa(1)];
yn=[ya;ya(1)];        
q=max(size(xn));
%
for i=1:q
    if xn(i) < 0
        xn(i)=xn(i)+360;
    end
end    
%
if min(xn) < 0 && max(xn) > 0
    long=wrapTo180(long);
elseif max(xn) < 0
    long=long-360;
end    
%
% If polygon is closed, find points in polygon
%
passi=zeros(n,m)+1;   % Set passi to unity if line segments are not a closed polygon
polytype='open';
if abs(xa(1)-xb(end)) <= 0.01 && abs(ya(1)-yb(end)) < 0.01
    polytype='closed';
    [passi]=inpolygon(long,lat,xn,yn);
end               
[passe,xint,yint,jint,kint,kfrac] = seg(long,lat,xa,ya,xb,yb);   
end