function [nint,xint,yint,jint,kint,kfrac] = boxm(xtrack,ytrack,xa,ya,xb,yb)
%
%     This function determines whether a set of n tracks (given by 
%     coordinates xtrack,ytrack) intersects a series of m-1 line segments
%     whose end points are given by xa(m), ya(m), xb(m), yb(m). Nint=0  
%     means no intersection; nint=1 means intersection. The last point may
%     equal the first, in which case one has a closed polygon. In this  
%     case, the routine also checks for tracks that lie entirely within the  
%     polygon. For this reason, the segments must be specified going  
%     CLOCKWISE around the polygon.
%
%     The quantities xint and yint constitute the first intersection point,
%     along the line segment numbered jint and the kint'th point along the
%     track. In the case of a closed polygon, if the track is entirely 
%     within the polygon, jint is set equal to -1 and xint=yint=0.0.
%     K. Emanuel   Last modified January, 2009.  
%     Copyright 2009 WindRiskTech L.L.C.
%
%-------------------------------------------------------------------------
[n,nd]=size(xtrack);
m=max(size(xa));
for i=1:m,
    if xa(i) < 0
        xa(i)=xa(i)+360;
    end
    if xb(i) < 0
        xb(i)=xb(i)+360;
    end
end    
%
% default values
%
nint=zeros(1,n);
jint=zeros(1,n);
kint=zeros(1,n);
xint=zeros(1,n);
yint=zeros(1,n);
kfrac=zeros(1,n);
%
[dum, jmax]=min(abs(ytrack),[],2);
jmax=jmax-1;
jmax=max(jmax,2);
%
for k=1:n,
%
nswitch=0;
%
for i=1:jmax(k)-1,
    x1=xtrack(k,i);
    x2=xtrack(k,i+1);
    y1=ytrack(k,i);
    y2=ytrack(k,i+1);
    for j=1:m,
          x3=xa(j);
          y3=ya(j);
          x4=xb(j);
          y4=yb(j);
%
          denom=(y4-y3).*(x2-x1)-(x4-x3).*(y2-y1);
          if abs(denom) >= 1e-8
           ua=((x4-x3).*(y1-y3)-(y4-y3).*(x1-x3))./denom;
           ub=((x2-x1).*(y1-y3)-(y2-y1).*(x1-x3))./denom;
           if ua >= 0 & ua <= 1 & ub >= 0 & ub <= 1
            nint(k)=1;
            xint(k)=x1+ua.*(x2-x1);
            yint(k)=y1+ua.*(y2-y1);
            jint(k)=j;
            kint(k)=i;
            kfrac(k)=ua;
            nswitch=1;
            break
           end 
          end 
    end 
    if nswitch == 1
        break
    end    
end 
%
if nint(k) == 0 & abs(xb(m)-xa(1)) < 0.01 & abs(yb(m)-...
     ya(1)) < 0.01
      nint(k)=1;
      jint(k)=-1;
      for j=1:m,
           a=(ytrack(k,1)-ya(j)).*(xb(j)-xa(j));
           b=(xtrack(k,1)-xa(j)).*(yb(j)-ya(j));
           if a > b 
            nint(k)=0;
            jint(k)=0;
           end
      end 
end 
end
        