% OVERLAPCORR Compute correlation introduced by segment overlapping
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% OVERLAPCORR Compute correlation introduced by segment overlapping in WOSA
% spectral estimations. It estimates the term contributing to the variance
% because of segment overlapping.
% 
% CALL 
% 
% R = utils.math.overlapCorr(w,N,T)
% [R,n] = utils.math.overlapCorr(w,N,T)
% 
% INPUT
% 
% - w, window samples, Nsx1 double, Ns must be the effective length of the
% segments used for spectral estimation. E.g. For a periodogram Ns is equal
% to the length of the data series. For a WOSA estimation Ns is the length
% of each averaging segment.
% - N total length of data series, 1x1 double
% - navs, number of averages, 1x1 double
% 
% REFERENCES
% 
% D. B. Percival and A. T. Walden, Spectral Analysis for Physical
% Applications (Cambridge University Press, Cambridge, 1993) p 292.
% 
% L Ferraioli 09-03-2011
%
% $Id: overlapCorr.m,v 1.1 2011/03/28 16:37:23 luigi Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function varargout = overlapCorr(w,N,navs)
  
  Ns = numel(w);
  % willing to work with columns
  [nn,mm] = size(w);
  if nn<mm
    w = w.';
  end
  
  % make suaqre integrable
  a = sqrt(sum(w.^2));
  w = w./a;

  n = floor((N-Ns)/(navs-1));
  win = [w; zeros((navs-1)*n,1)];
  
  R = 0;
  for kk=1:navs-1
    ew = zeros(size(win));
    ew(kk*n+1:kk*n+Ns) = win(1:Ns);
      
    R = R + (navs-kk)*abs(win.'*ew)^2;   
  end
  R = R./navs^2;
  
  if nargout == 1
    varargout{1} = R;
  else
    varargout{1} = R;
    varargout{2} = n;
  end
  

end