%trace_dist: calculates the distance between trace XI and every trace in XJ.
%            the distance between traces is the average squared euclidean distance
%            with the added condition that the traces be of approximately
%            equal lengths (within 5s).  Otherwise, the distance is given
%            to be impossibly large.  This method is modeled after the
%            distance functions used by matlab function 'linkage.'  More
%            information can be found in the matlab documentation.
%   Inputs:
%       XI : an intensity trace to calculate the distance from
%       XJ : a matrix of intensity traces which is n x m where n is the 
%            number of traces to be compared to XJ and m is the length of 
%            these traces.
%   
%   Output:
%       d  : the vector of distance between XI and XJ
%           
% Nathan Willy, Kural Group, Ohio State University, willy.2@osu.edu
%

function d = trace_dist(XI,XJ) 

    %create output vector
    d=zeros(size(XJ,1),1);
    %find length of non-zero values in XI
    len=length(find(XI));
    
    %iterate through all traces in XJ
    for(i=1:size(XJ,1))
        %find length of non-zero values in current trace
        len2=length(find(XJ(i,:)));

        %the distance is a very large number if lengths of the traces are
        %too different
        if(abs(len-len2)>5)
            d(i)=10^10;
        %otherwise, the distance is the mean, squared euclidean distance
        else
            d(i)=sum( ( XI(1:max(len,len2)) - XJ(i,1:max(len,len2)) ).^2 )/max(len,len2);
        end
    end
    
end