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

% INTERACTIVEORFSYSID =
%    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,alpha] = interactiveORFsysid(u,y)
%  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
%   alpha = the poles of the ORF 
%  input:
%   u = input signal  (column vector !)
%   y = output signal (column vector !)
%
%  See also: ORFsysidC, ORFsysidD1, ORFsysidD2, 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
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;

alpha = [0]; % alpha_0 = 0
theta(1,1) = x(:,1)'*Y;
Yhat = x(:,1)*theta(1,1);
normY = norm(Y);
err = norm(Y-Yhat)/normY

stop = input('Press 0 if you want to continue, 1 to quit >> '); 
k = 2;
while (stop==0),
   alpha(k) = input('Give the next pole >> ');
   while (abs(alpha(k))>=1),
      alpha(k) = input('Pole outside unit disc!!!/n Give a new pole >> ');
   end
   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;
   % IDENTIFICATION
   theta(k,1) = x(:,k)'*Y;
   newYhat = Yhat + x(:,k)*theta(k,1);
   err = norm(Y-Yhat)/normY
   delete = input('Press 1 if you want to delete this pole, 0 if not >> ')
   if (delete==0),
      Yhat = newYhat;
      k = k+1;
   end
   stop = input('Press 0 if you want to continue, 1 to quit >> ');
end

if (size(L,1)==1),
   L = transpose(L); % L --> column vector
end
