% findpairs
%
% find the closest approach between all possible drogued drifter pairs
% in the data set.

if (1); %~exist('id');
    load world lon lat t id drogue
    q=find(drogue<1);
    truncatedrift;
end;

ID=unique(id);
LatP=[]; LonP=[]; rP=[];  idP=[];  tP=[];

% loop through unique IDs
for i=1:length(ID);
    fprintf('%d of %d\n',i,length(ID));
    q1=find(id==ID(i));
    
    % find all other concurrent drifters
    q=find(t>=min(t(q1)) & t<=max(t(q1)) & id~=ID(i));
    ID2=unique(id(q));
    
    for j=1:length(ID2);
        q2=find(id==ID2(j));
        
        if ~isempty(intersect(t(q1),t(q2))); 
            [ti,q1b,q2b]=intersect(t(q1),t(q2));
            if (length(ti)>5)
                lon1=lon(q1(q1b));
                lat1=lat(q1(q1b));
                lon2=lon(q2(q2b));
                lat2=lat(q2(q2b));
                t1=t(q1(q1b));
                
                dlon=abs(lon1-lon2);
                q=find(dlon>180);
                dlon(q)=360-dlon(q);
                
                d=dlon.^2+(lat1-lat2).^2; 
                q=find(d==min(d)); q=q(1);
                if (d(q)<10)
                    idP=[idP; [ID(i) ID2(j)]];
                    LatP=[LatP; [lat1(q) lat2(q)]];
                    LonP=[LonP; [lon1(q) lon2(q)]];
                    rP=[rP; sw_dist([lat1(q) lat2(q)],[lon1(q) lon2(q)],'km')];
                    tP=[tP; t1(q)];
                end;
            end;
             
        end;
    end;   % loop over j (concurrent drifters)

    % remove drifter ID(i) from record
    q=find(id==ID(i));
    truncatedrift;
end;

save pairs idP LatP LonP rP tP

