function [cor,lags] = xcor(dat1,dat2)

%
% [cor,lags] = xcor(dat1,dat2)
%
% Cross correlation calculation
% the two data sets must be the same length
% if dat1 = dat2 (autocorr.) then output is onesided
% if dat1 |= dat 2 (crosscorr.) then twosided
%
% positive lags mean dat2 leads dat1

n = length(dat1);

% check for auto/cross correlation
if (dat1 == dat2)
    sided = 1;
    lags = 0:(n-1);
else
    sided = 2;
    lags = (1-n):(n-1);
end;

x = dat1; y = dat2; xm = mean(x); ym = mean(y);
covxy = zeros(length(lags),1);

if ( sided == 1 )
    for i=lags
        covxy(i+1) = sum( (x(i+1:n)-xm).*(y(1:n-i)-ym) );
    end
elseif ( sided == 2 )
    for i=lags
        if i<0
            i = abs(i);
            covxy(n-i) = sum( (x(1:n-i)-xm).*(y(i+1:n)-ym) );
        else
            covxy(i+n) = sum( (x(i+1:n)-xm).*(y(1:n-i)-ym) );
        end
    end
end

covxy = covxy./n;

cor = covxy./sqrt(var(x)*var(y));
