%  LEVSOLVERBANDHSS Solves a system of equations for a 
%                   strongly nonsingular band plus semiseparable matrix
%    
%    X=LEVSOLVERBANDHSS(U,V,B,d) is the solution of the system (B+S)X=d,
% 
%    B has to be a matrix of dimension n times l+1 where l is the band
%    width of B. More information concerning this representation can be
%    found in the routine BBAND
%
%    The matrix S is a higher order generator semiseparable matrix represented
%    with two vectors U,V
%
%    d is the right-hand side
%
%   
%    Software of the MaSe - Group
%    mase-at-cs.kuleuven.ac.be
%    Revision Date: 15/04/2005

function x=LEVSOLVERBANDHSS(U,V,A,d)
  
  % let us start the initialization procedure
  % with n we denote the size of the matrix
  % with l we denote the band width
  % with p is meant the semiseparability rank
    
  [n,l]=size(A);
  l=l-1;
  [n,p]=size(U);
   
  %--------Help ----------------
  % the initial matrix P
  P=eye(p);
  P(p+1:l+p,p+1:l+p)=diag(ones(1,l-1),-1);
  % The right-hand side Q is built up using the R and the T
    % let us define the complete final right-hand side
  T=zeros(n,l);
  T(n-l+1:n,1:l)=eye(l); 
  

  % The first l times in the for loop are a little different, because we
  % reduce the complexity by not starting with a full right hand side 
  alpha=zeros(n,l+p);
  alpha(1,[1:p,p+l])=[-V(1,:),-1]./(U(1,:)*V(1,:)'+A(1,l+1));
  mu=zeros(n,1);
  mu(1)=d(1)/(A(1,l+1)+U(1,:)*V(1,:)');
  
  % initialization of the product Q'*Y  this is a (l+p) x (l+p) matrix
  qy=[V(1,:),zeros(1,l-1),1]'*alpha(1,:);
  qx=[V(1,:),zeros(1,l-1),1]'*mu(1);
  
  % the main loop in which we use always the previous solution
  for k=2:n
    
    % initialize a help var c
    % Because the product c*qy appears two times
    c=[U(k,:),A(k,1:l)];
    cqy=c*qy;
    qyc=qy([1:p,p+2:l+p],:)*c';
    qyc(1:p)=qyc(1:p)+V(k,:)';  
    
    % Calculate the denominator of alpha
    denominator=cqy*c'+U(k,:)*V(k,:)'+A(k,l+1);
    
    % the computation of the vector alpha
    alpha(k,:)=[-V(k,:)-cqy(1:p),-cqy(p+2:l+p),-1]/denominator;
    mu(k)=(d(k)-c*qx)/denominator;
  
    % Calculation of the new Product Q'*x
    qx=[qx([1:p,p+2:l+p])+qyc*mu(k);mu(k)];
    
    % Calculation of the new Product Q'*Y
    qy=[qy([1:p,p+2:l+p],[1:p,p+2:l+p])+qyc*alpha(k,1:l+p-1),qyc* ...
            alpha(k,l+p)];
    qy=[qy;alpha(k,:)];
    
   end
  
  
  % This part is excluded from the main loop, because in this way, we
  % can dramatically reduce the complexity of the overall algorithm
  
  
  % M is the vector of length p used as the factor
  M=zeros(l+p,1);
  x(n)=mu(n);
  
  % starting the construction of y
  for i=n-1:-1:1
    % Updating the factor M
    M(1:p,1)=M(1:p)+U(i+1,:)'*x(i+1);
    M(p+2:l+p,1)=M(p+1:l+p-1)+A(i+1,2:l)'*x(i+1);
    M(p+1,1)=A(i+1,1)*x(i+1);
    
    % the next element in the solution vector
    x(i)=mu(i)+alpha(i,:)*M;
  end
 
  
  x=x';