function [R1] = update_QR_add_pair(Psi,R1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Updates the R part of the QR decomposition of Psi
% after a new pair has been computed and added to S, Y, and Psi.
%
% "On efficiently computing the eigenvalues of limited-memory
% quasi-Newton matrices"
% by Jennifer Erway and Roummel Marcia
%
% Copyright (2015): Jennifer Erway and Roummel Marcia
%
% The technical report and software are available at
% www.wfu.edu/~erwayjb/publications.html
% www.wfu.edu/~erwayjb/software.html
%
%
% This code is distributed under the terms of the GNU General Public
% License
% 2.0.
%
% Permission to use, copy, modify, and distribute this software for
% any purpose without fee is hereby granted, provided that this entire
% notice is included in all copies of any software which is or includes
% a copy or modification of this software and in all copies of the
% supporting documentation for such software.
% This software is being provided "as is", without any express or
% implied warranty. In particular, the authors do not make any
% representation or warranty of any kind concerning the merchantability
% of this software or its fitness for any particular purpose.
%---------------------------------------------------------------------------
%
% Inputs: Psi is a mx(k+1) matrix
% R1, the leading kxk upper triangular matrix of the QR decomposition
% of Psi before the newest column was added to Psi
%
% Output: R1, the (k+1)x(k+1) upper triangular matrix of the QR
% decomposition of Psi after the addition
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
feedback = 1; %flag
[m,kplus] = size(Psi);
if rank(R1)==size(R1,2) %compute numerical rank to MATLAB tolerances
u_1 = R1'\(Psi(:,1:kplus-1)'*Psi(:,kplus));
eta = sqrt((norm(Psi(:,kplus)))^2 - (norm(u_1))^2);
R1 = [R1 u_1; zeros(1,kplus-1) eta];
else
if feedback
fprintf('\nR is not full rank... redoing full QR decomposition\n');
end
R = qr(Psi);
R1 = R(1:kplus,1:kplus);
end