function [ D, psin, beta ] = BioBack( D, psin, beta, j )
% BioBack deletes the requested vector j from a given basis taken from a dictionary
%
% Modifies the corresponding biorthogonal basis and orthonormal basis (obtained by
% modified Gram-Schmidt) and retuned the re-ordered dictionary (this is the only diference
% with biodelete, which does not deal with the whole dictionary).
%
% Usage:    [ D, psin, beta ] = BioBack( D, psin, beta, j );
%
% Inputs:
%   D       Dictionary, first kb vectors D(:,1:kb) are the selected basis
%   psin    orthonormal basis spanning the same space as D(:,1:kb) kb=size(psin,2
%   beta    biorthogonal basis to D(:,1:kb),  kb=size(beta,2)
%   j       index of function to eliminate  
%  
% Outputs:
%   D       updated (rearranged) dictionary (D(:,1:kb-1) is the new basis)
%   psin    updated orthonormal basis spanning the same space as D(:,1:kb-1)
%   beta    updated biorthogonal basis to D(:,1:kb-1)
%
% References:
%   L. Rebollo-Neira, "Recursive bi-orthogonalisation approach and orthogonal projectors",
%   math-ph/0209026 (2002).
%
% See also NBioDelete, NBioDictDel, BioDictDel.

% See   http://www.ncrg.aston.ac.uk/Projects/HNLApprox/
%       http://www.nonlinear-approx.info/

name='BIOBACK';    
[N,k]=size(D);
kb=size(beta,2);
if (j<1) | (j>k)
  fprintf('%s: Required index %d is out of range (%d atoms)\n',name,j,k);
  return;
end  

b=beta(:,j);
up=psin(:,j);
beta(:,j)=[];
nor=b'*b;
beta=beta-b*(b'*beta)/nor;
%downdating of psin
R=psin(:,1:kb)'*D(:,1:kb);
dummy=R(:,j);R(:,j)=[];R(:,kb)=dummy;
for i=j:kb-1
  p=[i i+1];
  [G,R(p,i)]=planerot(R(p,i)); %find appropriate Givens rotation
  R(p,i+1:kb)=G*R(p,i+1:kb);   %apply Givens rotation to R(p,i+1:k)
  psin(:,p)=psin(:,p)*G';      %apply Givens rotation to psin(:,p)
end

ud=D(:,j);D(:,j)=[];D(:,k)=ud;
psin(:,kb)=[];%psin(:,k)=ud;

%Last modification Laura Rebollo-Neira 2008

%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.
