function [theta,L,err]=ORFsysidD2(U,Y,alpha)

% ORFSYSIDD2 =
%    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] = ORFsysidD2(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
%  input:
%   U/Y   = z-transform of the in/out-put signal in the points
%           exp(I*2*pi*(k-1)/length(U))
%   alpha = the poles of the ORF 
%
%  See also: ORFsysidC, ORFsysidD1, 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);

I=sqrt(-1);
t=exp(I*2*pi/N*transpose([0:N-1]));
weight = abs(transpose(U)).^2;
W=sum(weight);

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);