% INV_UNSYM_TRID Inverts an unsymmetric tridiagonal matrix returning
% four vectors, u,v,p,q describing the matrix.
%         
%
%       [u,v,p,q]=INV_UNSYM_TRID(subd,d,supd)
%       subd contains the subdiagonal of the tridiagonal T
%       d contains the diagonal of the tridiagonal T
%       supd contains the superdiagonal of the tridiagonal T
%       u,v,p,q are the generators of the unsymmetric semiseparable matrix
%       The inverse S of T:
%       S= tril(u.'*v)+triu(p.'*q,1);
%
%       This algorithm is described in (and the references therein):
%       Vandebril R., Van Barel M. and Mastronardi N., 
%       ``Matrix Computations and Semiseparable Matrices I: 
%       Linear Systems'', xviii+575 pp., 
%       The Johns Hopkins University Press, Baltimore, 2007 
%       (ISBN-13: 978-0-8018-8714-7). 
%       http://www.press.jhu.edu/books/title pages/9085.html
%       ---> See Chapter 7, Section 7.2.3
%
%       Raf Vandebril
%       raf.vandebril - a - cs.kleuven.be
%       Revision Date: 1/9/2008



function [u,v,p,q] = Inv_Unsym_Trid(b,a,c)

  
  % Initialization of the length of the loop
  n=length(a);
  
  if n==1
    u=inv(a);
    v=[];
    p=[];
    q=[];
  
  else
    p(1)=1; 
    p(2)=-a(1)/c(1);
    for i=3:n
      p(i)=-(a(i-1)*p(i-1)+b(i-2)*p(i-2))/c(i-1);
    end
    
    v(1)=1; 
    v(2)=-a(1)/b(1);
    for i=3:n
      v(i)=-(a(i-1)*v(i-1)+c(i-2)*v(i-2))/b(i-1);
    end
    
    q(n)=1/(a(n)*p(n)+b(n-1)*p(n-1)); 
    u(n)=p(n)*q(n)/v(n);
    for i=(n-1):-1:2
      q(i)=(1-c(i)*v(i)*u(i+1))/(a(i)*p(i)+b(i-1)*p(i-1));
    u(i)=p(i)*q(i)/v(i);
    end
    q(1)=(1-c(1)*v(1)*u(2))/(a(1)*p(1));
    u(1)=p(1)*q(1)/v(1);
  end