function [X,Y,Xlagflag] = lagcorrection(X,Y,maxlags)

Xlagflag=0;  %defines default lag time

% calculate y/x correlation over lag range of +/- 16 points
[XYcorr,xlags] = xcov(Y,X,maxlags,'coeff');
    
% find index for minimum in correlation
[minXYcorr, minXLagIndex] = min(XYcorr);
[maxXYcorr, maxXLagIndex] = max(XYcorr);

if abs(maxXYcorr)>abs(minXYcorr)
    Xlagflag = maxXLagIndex-maxlags-1;
elseif abs(maxXYcorr)<abs(minXYcorr) 
    Xlagflag = minXLagIndex-maxlags-1;
end    
% Compute # of data points to shift data where total #lags is maxlags*2+1.
%    lagflag = -maxlag for index = 1
% Xlagflag = minXLagIndex-maxlags-1;

% Compute motion corrected winds
% Shift w data by n=lagflag points and sum uvw and uvwplat.
% Positive lagflag means Y (motion) is delayed compared to X (wind).
if Xlagflag > 0,
    X(1:length(X)-Xlagflag) = X(1:length(X)-Xlagflag) +Y(Xlagflag +1:length(X));
else
    X(-Xlagflag +1:length(X)) = X(-Xlagflag +1:length(X)) + Y(1:length(X)+ Xlagflag);
end
