% CplxSym Transforms a normal matrix via unitary similarity 
%             to complex symmetric form
%
%       C=CplxSym(N)
%       Outputs a unitary similar complex symmetric matrix C=Q'*N*Q,
%       N is assumed to be normal.
%
%       [Q,C]=CplxSym(N)
%       Outputs a unitary similar complex symmetric matrix C=Q'*N*Q, and
%       the unitary matrix Q, N is assumed to be normal.
%
%       [Q,C,U,B,V]=CplxSym(N)
%       Outputs a unitary similar complex symmetric matrix C=Q'*N*Q, and
%       the unitary matrix Q, N is assumed to be normal. Also U,B and V
%       are given where N = U B V^*.
%
%       C=CplxSym(N,redtype)
%       [Q,C]=CplxSym(N,redtype)
%       [Q,C,U,B,V]=CplxSym(N,redtype)
%       Outputs a unitary similar complex symmetric matrix C=Q'*N*Q, and
%       the unitary matrix Q, N is assumed to be normal.
%       For transforming N to complex symmetric form either U or V is
%       used in the bidiagonal factorization N = U B V^*.
%
%       When not specified  Q is taken equal to U
%       redtype='U'      Q is taken equal to U    
%               'V'      Q is taken equal to V
%
%
%       Raf Vandebril
%       Revision Date: 07 V 09


% REMARK: THIS CODE IS JUST A TESTCODE, THE HOUSEHOLDERS ARE NOT YET
% PERFORMED EFFICIENTLY. Just implemented as dense matrices.

function [Q,C,Ql,A,Qr]=CplxSym(A,redtype)

  % Initialization
  n=size(A,1);
  I=sqrt(-1);

  % compute bidiagonal reduction of A. This is not done effeciently
  % We compute Ql A Qr = B, where B is bidiagonal.
  Aorig=A;
  Ql=eye(n);
  Qr=eye(n);
  for i=1:n-1
    [QA,RA]=qr(A(i:n,i));
    A(i:n,:)=QA'*A(i:n,:);
    Ql(i:n,:)=QA'*Ql(i:n,:);
    M=A(i,i+1:n)';
    [QM,RM]=qr(M);
    A(:,i+1:n)=A(:,i+1:n)*QM;
    Qr(:,i+1:n)=Qr(:,i+1:n)*QM;
  end
  
  
  if (~exist('redtype'))
    redtype='U';
  end
  
  
  if (exist('redtype'))
    switch redtype
     case 'V'
      % This means, use the transformation from the right    
      C=Qr'*Aorig*Qr; 
      Q=Qr; 
     case 'U'
      % Scale now the matrix Ql, in fact this is not necessary when
      theta=angle(A(n,n));
      A(n,:)=exp(-I*theta)*A(n,:);
      Ql(n,:)=exp(-I*theta)*Ql(n,:);
      
      % Perform the similarity transformation on the matrix A
      C=Ql*Aorig*Ql';
      Q=Ql';
     otherwise
      warning('Option for redtype not allowed')
      help CplxSym;
      error('Routine terminated')
    end
  end

  if (nargout==1)
    Q=C;
  end

  Ql=Ql';
  %Qr=Qr';
  
    
  