% Let us check if deflation after a QR-step is possible
% Deflation is checked by a relative criterion.

% Considering the special cases discussed in the article:
% H(n,n-1) and H(2,1) cannot be computed according the loop.

% All elements are checked, whether they satisfy a specific relative
% criterion. IMPORTANT: it might be possible that more than 1 element is
% smaller than the relative criterion. Hence instead of only 1
% subdivision, it might be possible that several blocks are created.
% A vector deflateproblems keeps track of the positions, where small
% elements were found.



% Initialize the deflation criterion
deflateproblems=[];


% Special Case 1, we cannot compute H(2,1) via the loop
if i1==1
  % This is only for the first element since there is an interaction
  x=retrievecolumn(G,B,u,v,1);
  if ( abs(x(2)) < defcrit*(abs(x(1))+abs(B(2,3))))  
    % Store the position of the zero 
    deflateproblems=[1];
    globaldeflateblocks(end+1)=1;
  end
  
end


% Define the end of the loop
if i2==n
  endl=i2-2;
else
  endl=i2-1;
end



% The main loop check deflation related to the subdiagonal elements
for idef=i1+1:endl
  
    % defcrit is an arbitrary value determining how small an element
    % should be before deflation will be applied
    if ( abs(B(idef,1)) < defcrit*(abs(B(idef-1,1))+abs(B(idef,2))))
            
      % Store the position of the zero
      deflateproblems(end+1)=idef;    
      globaldeflateblocks(end+1)=idef;
    end
end



% Special case 2, we cannot compute element H(n,n-1) via the loop
if i2==n
  % Check the element in position H(n,n-1)
  x=retrievecolumn(G,B,u,v,n-1);

  if ( abs(x(3)) < defcrit*(abs(x(2))+abs(B(n,3))))
    
    % Store the position of the zero 
    deflateproblems(end+1)=n-1;
    globaldeflateblocks(end+1)=n-1;
  end
end



if (deflateproblems) % If deflateproblems is not empty
  
  % Assign true, so that the while loop stops iterating
  converged=true;
  
  % The matrix can be subdivided, hence remove the problem we just
  % have taken care of
  ibegin=ibegin(2:end);
  iend=iend(2:end);
  
  
  % Reassign the different subproblems
  for npr=1:length(deflateproblems)
    % Problem size needs to be bigger than 3  
    if (deflateproblems(npr)-i1 > 2) 
      % When it is bigger than 3 add it to the cue
      ibegin(end+1)=i1;
      iend(end+1)=deflateproblems(npr);
    end
    i1=deflateproblems(npr)+1;
  end
  
  % Add possibly the last problem to the cue
  if (i2-i1 > 2 ) % add it to the end of the cue
    ibegin=[ibegin,i1];
    iend=[iend,i2];
  end
  
  
end
      