%computes lag
% LB  
function Xlagflag = findlag (X,Y,maxlags,plotit)

ii=find(~isnan(X)&~isnan(Y));
[XYcorr,xlags] = xcov(Y(ii),X(ii),maxlags,'coeff');
[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
% Positive lagflag means Y is delayed compared to X .
if plotit
    figure;plot(xlags,XYcorr);grid
end
