% function [newMin, newExtremes] = lookAhead(D, c, numCl, discardedIndex) 
% lookAhead looks ahead in the dissimilarity matrix D (defined over 
% numCl clusters) that results from merging two clusters into cluster c, 
% and returns the closest cluster(s) (with the associated dissimilarity 
% value) to cluster c.
%
% This file is part of Cluster4MetaAnalysis.
%     Cluster4MetaAnalysis 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 3 of 
%     the License, or (at your option) any later version.
% 
%     Cluster4MetaAnalysis 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 Cluster4MetaAnalysis.  If not, see
%     <http://www.gnu.org/licenses/>.


function [newMin, newExtremes] = lookAhead(D, c, numCl, discardedIndex)


% look for minimum in the row of D corresponding to cluster c
R = getRow(c, numCl);
newMin = min(D(R));

% multiple minima might exist, let us find all of them
temp = find(D(R) == newMin);
numNewExtr = length(temp);
newExtremes = zeros(1, numNewExtr);
for i=1:numNewExtr
    [e1 e2] = getMatrixIndexes(R(temp(i)), numCl);
    % let us get rid of c
    newExtremes(i) = setdiff([e1 e2], c);
    % index remapping might be required (indexes in D are shifted to the 
    % left, starting from discardedIndex, with respect to the current 
    % dissimilarity matrix - recall that we are looking into the 
    % dissimilarity matrix we get one step ahead from now)
    if (newExtremes(i) >= discardedIndex)
       newExtremes(i) = newExtremes(i) + 1;
    end
end

