function [theta,L,err,moments]=ORFsysidD1(u,y,alpha)

% ORFSYSIDD1 =
%    SISO System identification using orthogonal rational 
%    functions phi_k, with user defined poles and
%    with respect to a weight defined by the input.
%    The identification is based on a discrete inner product. 
%
% use: [theta,L,err,moments] = ORFsysidD1(u,y,alpha)
%  output:
%   theta  = coefficients in expansion: G_hat = sum_k theta_k phi_k
%   L      = reflection coefficients of the ORF
%   err    = relative error of the approximation
%   moments= the moments 
%  input:
%   u     = input signal  (column vector !)
%   y     = output signal (column vector !)
%   alpha = the poles of the ORF 
%
%  See also: ORFsysidC, ORFsysidD2, interactiveORFsysid, ORFcalcul

% Patrick Van gucht and Adhemar Bultheel, september, 11, 2000.

%initialization
if (size(u,1)<size(u,2)), % row vector --> column vector
   u=transpose(u);
end
if (size(y,1)<size(y,2)), % row vector --> column vector
   y=transpose(y);
end

N = length(u); % Length of the signal
n = length(alpha); % number of ORF
u = u(1:N);
y = y(1:N);

moments = conv(conj(u),flipud(u)); %to compute the weights
moments = moments(N:2*N-1); 
I=sqrt(-1);
t=exp(I*2*pi/N*transpose([0:N-1]));
hulp = fft(moments);
weight = transpose(hulp + conj(hulp) - moments(1));
W=sum(weight);

U = fft(u); 
Y = fft(y); 

phi(:,1)=ones(N,1)/sqrt(W);     
phistar(:,1)=ones(N,1)/sqrt(W); 
x(:,1)=phi(:,1).*U;
xstar(:,1)=phistar(:,1).*U;

L = zeros(n,1);
alpha = [0 alpha];
for k=2:n+1,
   hulp1 = (t-alpha(k-1))./(1-alpha(k)'*t).*conj(phi(:,k-1));
   hulp2 = (1-alpha(k-1)'*t)./(1-alpha(k)'*t).*conj(phistar(:,k-1));
   L(k-1) = -(weight*hulp1)/(weight*hulp2); % reflectioncoefficient
   e_k = sqrt((1-abs(alpha(k))^2)/((1-abs(alpha(k-1))^2)*(1-abs(L(k-1))^2)))./(t-alpha(k));
   hulp =  (1-alpha(k-1)'*t).*phi(:,k-1);
   hulpstar = (t-alpha(k-1)).*phistar(:,k-1);
   phi(:,k) = e_k.*(hulp + L(k-1)'*hulpstar);
   phistar(:,k) = e_k.*(L(k-1)*hulp + hulpstar);
   x(:,k) = phi(:,k).*U;
   xstar(:,k) = phistar(:,k).*U;
end

% IDENTIFICATION
theta = x'*Y;
Yhat = x*theta;
err = norm(Y-Yhat)/norm(Y);
