function [D,beta]=FrInsert(D,beta,atom,tol,dual);
% FrInsert adds a vector to a frame. It also appropriately
% modifies the corresponding dual frame.
%  
% Usage: [D,beta]=nfrinsert(D,beta,atom,tol);
%  
% Inputs:
%   D    frame
%   beta dual  frame to D
%   atom new  vector to be incorporated into the frame
%   tol  tolerance (optional parameter) to decide linear dependence
%        default value = 1.0000e-7
%   dual if atom is linearly dependent dual is an arbitrary vector 
%         default dual=atom
%  
% Outputs:
%   D    updated frame
%   beta updated dual frame of D
%  
% References:
%  [1] L. Rebollo-Neira, ``Constructive updating/downdating of oblique projectors: a generalization of the Gram-Schmidt process'',
% Journal of Physics A: Mathematical and Theoretical}, Vol(40), 6381-6394 (2007)
%
% This routine is  equivalent to NBioInsert  if the new atom is independent 
%
% see http://www.ncrg.aston.ac.uk/Projects/HNLApprox/ 
  
name='FrInsert';  

if nargin==4, dual=atom; end 
if nargin==3, tol=1.0000e-7; dual=atom; 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

%modified!!!!!! from NBIOINSERT (the former seemed not to work well for a 
%redundat frame when u is redundta?
u=u-D*beta'*u; %re-orthogonalization
u=u-beta*D'*u; %orthogonalization

psi_norm=norm(u);
%test of linear dependancy
if psi_norm<tol
%for the canonical dual 
gba=beta'*atom;
dual=beta*gba/(1+gba'*gba);
 beta=beta-dual*(atom'*beta);
 beta(:,k+1)=dual;
 fprintf('%s: New atom was found dependant.\n Its norm after substraction its component in selected space is %g\n',name,psi_norm);
else
  temp=u/(psi_norm*psi_norm);
%for i=1:k
%  temp=temp-beta(:,i)*(D(:,i)'*temp);
%end test follows!!!!!!!!!!!!!!!!!!!!!!!!!  
temp=temp-D*beta'*temp;
temp=temp-beta*D'*temp;

beta=beta-temp*(atom'*beta);  
beta(:,k+1)=temp;
 fprintf('%s: New atom was found INDEPENDAT.\n Its norm after substraction its component in selected space is %g\n',name,psi_norm);
end
%basis updating 
D(:,k+1)=atom;

%Laura Rebollo-Neira (2008)

