function [ro,ccf] = fccf(x,y)
% FFT-BASED COMPUTATION OF THE CROSS-CORRELATION/COVARIANCE FUNCTION ESTIMATE
%        (suitable for long sequences of well-factorizable length)
% function [ro,ccf] = fccf(x,y)
% x,y ... time series data vectors of length n
% ro  ... estimate of the cross-correlation function of length n/4 (column vec.)
%         (leading significant part only)
% ccf ... full estimate of the cross-covariance function of length n.
%         (column vector)

% (C) 1996, V. Vesely, Masaryk University of Brno (Czech Republic)
%
if size(x,1)==1, x=x.'; end
if size(y,1)==1, y=y.'; end
if size(x,2)>1 , error('x is not a vector'); end
if size(y,2)>1 , error('y is not a vector'); end
n  = length(x);
if n~=length(y), error('the lengths of x and y differ'); end
if n<50
   disp('WARNING: few samples (less than 50) to get a reliable estimate');
end
realdata = isreal(x) & isreal(y);
x0 = x-mean(x); y0 = y-mean(y);
normx0 = norm(x0); normy0 = norm(y0);
x0 = [x0; zeros(n-1,1)]; y0 = [y0; zeros(n-1,1)];
x0 = fft(x0); y0 = fft(y0);
z  = x0.*conj(y0);
z  = ifft(z);
if realdata, z = real(z); end
ccf = z(1:n)./n;
n4 = ceil(n/4);
ro = z(1:n4)./(normx0*normy0);
