function [zz,ee,mer] = canc(x,s,u,l,iter)
%CANC   Correlated Adaptive Noise Cancelling
%   For two vectors x=signal+noise1 and s=signal+noise2, CANC extracts
%   the correlated signal and removes the noise1 and noise2. The inputs
%   are the two vectors x and s, the convergence factor u, the filter
%   length l and the number of iterations iter.

%   References:
%   Hattingh, M. (1988): A new data adaptive filtering program to remove
%   noise from geophysical time- or space-series data. Computers and Geo-
%   sciences, 14: 467-480.
%   Haykin, S. (1991): Adaptive Filter Theory. Prentice-Hall, Englewood
%   Cliffs, New Jersey: 854.

[n1,n2]=size(s);n=n2;index=0; % Formatting
if n1>n2
    s=s';x=x';n=n1;index=1;
end
w(1:l)=zeros(1,l);e(1:n)=zeros(1,n); % Initialization
xx(1:l)=zeros(1,l);ss(1:l)=zeros(1,l);
z(1:n)=zeros(1,n);y(1:n)=zeros(1,n);
ors=s;ms(1:n)=mean(s).*ones(size(1:n));
s=s-ms;x=x-ms;ors=ors-ms;
for it=1:iter % Iterations
    for I=(l+1):(n+1) % Filter loop
		for k=1:l
            xx(k)=x(I-k);ss(k)=s(I-k);
        end
        for J=1:l
            y(I-1)=y(I-1)+w(J).*xx(J);
            z(I-1)=z(I-1)+w(J).*ss(J);
        end
            e(I-1)=ors(I-1-(fix(l/2)))-y(I-1);
        for J=1:l
            w(J)=w(J)+2.*u.*e(I-1).*xx(J);
        end
    end % End filter loop
	for I=1:n % Phase correction
		if I<=fix(l/2)
			yy(I)=0;zz(I)=0;ee(I)=0;
		elseif I>n-fix(l/2)
			yy(I)=0;zz(I)=0;ee(I)=0;
		else
			yy(I)=y(I+fix(l/2));
            zz(I)=z(I+fix(l/2));
			ee(I)=abs(e(I+fix(l/2)));
		end
			yy(I)=yy(I)+ms(I);
            zz(I)=zz(I)+ms(I);
    end % End phase correction
	y(1:n)=zeros(size(1:n));
	z(1:n)=zeros(size(1:n));
    mer(it)=mean(ee((fix(l/2)):(n-fix(l/2))).^2);
end % End iterations
if index==1 % Reformatting
    zz=zz';yy=yy';ee=ee';
end

