function [c, xm, xc, xs, ym, yc, ys] = lincor(x, y, ilag);
%LINCOR  Correlation between two sequences using  available data, 
%    ignoring NaNs.
% 
%    LINCOR(X,Y) returns the lagged correlation of X and Y
%    estimated from all available data
%    ignoring NaN-elements that indicate missing
%    values. 
% 
%    If all terms in the sum of the product and/or cross-product terms
%    contributing to a correlation is missing, the
%    correlation is set to zero.
%
%    [C, XM, XC, YM, YC] = LINCOR(X,Y) returns the vector of lagged 
%    correlation coefficients C from all available data, 
%
   
  error(nargchk(1,3,nargin))          % check number of input arguments 
  if isempty(x)                       % check for empty input.
    sx = NaN;
    return
  end
  if ndims(x) > 2,  error('Data must be vector'); end
  if ndims(y) > 2,  error('Data must be vector'); end

  if nargin < 2, flag = 1; end        % default: normalize by nt-1

  if length(x)==prod(size(x))         % if x is vector, make sure
    x = x(:);                         % it is a row vector
  end 
  
  if nargin < 3, ilag=0; end
  % center data
  [xc,xm,xs] = standardize(x);
  [m,n]   = size(xc);
  [yc,ym,ys] = standardize(y);
  [j,k]   = size(yc);
  
  % make sure that the two vectors have the same length
  if m ~= j
     error('lengths not equal')
  end
  % replace NaNs with zeros.
  inan    = find(isnan(xc));
  xc(inan)= zeros(size(inan));
  jnan    = find(isnan(yc));
  yc(inan)= zeros(size(jnan));
  % calculate correlation
  %  for ii=1:m-1
  c=0;
  ii=ilag+1;
  nt = 0;
  for jj=1:m
     kk=jj+ii-1;
     if (kk <= m)
        nt = nt+1;
        c = c+ xc(jj)*yc(kk);
     end
  end
c=c/(nt-1);