function [ D, beta ] = NBioInsert( D, beta, atom, tol )
% NBioInsert adds an atom to a basis and modifies the biorthogonal basis for the same space
%  
% Usage:    [ D, beta ] = NBioInsert( D, beta, atom, tol );
%  
% Inputs:
%   D       already selected basis 
%   beta    biorthogonal functions to D
%   atom    new atom to be incorporated into basis 
%   tol     tolerance (optional parameter) to decide linear dependence default value =
%           1.0000e-7 
%  
% Outputs:
%   D       updated basis   
%   beta    updated biorthogonal functions to D
%  
% References:
%   L. Rebollo-Neira, "Recursive bi-orthogonalisation approach and orthogonal projectors",
%   math-ph/0209026 (2002).
%
% See also BioInsert, NBioDictIns, BioDictIns.

% See   http://www.ncrg.aston.ac.uk/Projects/HNLApprox/
%       http://www.nonlinear-approx.info/
  
name='NBioInsert';  
if nargin<5, tol=1.0000e-7; end
[N,k]=size(D);
u=atom;

%simple tests of input data
%comment this 'if' for faster computations
if any([N,k]~=size(beta)) | ((N~=length(atom)) & N~=0) 
  error('%s: Bad size of input matrices',name);
end  

%case k=0 
if k==0
  psi_norm=norm(u);
  if psi_norm<tol
    fprintf('%s: The first atom has zero norm! (norm=%g)\n',name,psi_norm);
    return;
  end  
  D=u;
  beta=u/(psi_norm*psi_norm);
  return;
end  

%case k>0
%re-orthogonalization (twice)
for z=1:2 
  for i=1:k
    u=u-beta(:,i)*(D(:,i)'*u);
  end
end

psi_norm=norm(u);
%test of linear dependancy
if psi_norm<tol
  fprintf('%s: New atom was found dependant.\n Its norm after substraction its component in selected space is %g\n',name,psi_norm);
  return;
end  

temp=u/(psi_norm*psi_norm);
for i=1:k
  temp=temp-beta(:,i)*(D(:,i)'*temp);
end  
beta=beta-temp*(atom'*beta);  
beta(:,k+1)=temp;
%basis updating 
D(:,k+1)=atom;

%Last modification Laura REBOLLO-NEIRA (2009).
%
%Copyright (C) 2006 Miroslav ANDRLE and Laura REBOLLO-NEIRA
%
%This program is free software; you can redistribute it and/or modify it under the terms 
%of the GNU General Public License as published by the Free Software Foundation; either 
%version 2 of the License, or (at your option) any later version.
%
%This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
%without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
%See the GNU General Public License for more details.
%
%You should have received a copy of the GNU General Public License along with this program;
%if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
%Boston, MA  02110-1301, USA.
