function [D,beta]=FrInsertBlock(D,beta,gb,tol)
% FrInsertBlock adds vectors to a basis and gives the duals 
% spanning the same space
%
% Usage: [D,beta]=FrInsertBlock(D,beta,gb,tol);
%  
% Inputs:
%   D    basis 
%   gb   new vectors to be incorporated into the basis 
%   tol  tolerance (optional parameter) to decide linear dependence
%        default value = 1.0000e-7
%  
% Outputs:
%   D    updated basis 
%   beta updated biorthgonal basis 
%  
%
% or http://www.ncrg.aston.ac.uk/Projects/HNLApprox/
  
name='FrInsertBlock';  

if nargin==3, tol=1.0000e-7; end
[N,k]=size(D);
u=gb;

%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 based on BioInset copyright bellow
%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.
