function worstLMIdx = findWorstLM(obj)
% FINDWORSTLM finds the index of the worst local model, based on the local loss function.
%
%
% worstLMIdx = findWorstLM(obj)
%
%
% INPUT
%
%   obj          object     HiLoMoT object containing all relevant properties and methods.
%
% OUTPUT
%
%   worstLMIdx:  (1 x 1)    Index of the worst performing local model, i.e. highest
%                           local loss function value.
%
% HiLoMoT - Nonlinear System Identification Toolbox
% Benjamin Hartmann, 04-April-2012
% Institute of Mechanics & Automatic Control, University of Siegen, Germany
% Copyright (c) 2012 by Prof. Dr.-Ing. Oliver Nelles


% Find all leaf models that are not forbidden
idxAllowedLeafs = (obj.leafModels & obj.idxAllowedLM);

% Check the number of points in LMs
numberOfInputs = size(obj.input,2);
LMPoints = sum(obj.phi(:,idxAllowedLeafs),1);

% Number of LM points must be sufficient
% if any(LMPoints<numberOfInputs+1)
%     idxAllowedLeafs = ( idxAllowedLeafs & (LMPoints>numberOfInputs+1) );
%     obj.idxForbiddenLM = ( obj.idxForbiddenLM & sum(obj.phi,1)<numberOfInputs+1 );
%     disp('HUI!!')
% end

% Get all local loss function values (loop over all leafs that are allowed for further splitting)
localLFV = cell2mat(arrayfun(@(locobj) locobj.localLossFunctionValue, obj.localModels(idxAllowedLeafs), 'UniformOutput', false));
%
% i.e. 
% idx = find(idxAllowedLeafs);
% for idx
%   localLFV(idx) = obj.localModels(idx).localLossFunctionValue;
% end
%

if isempty(localLFV)
    % Evaluate new loss function values and update structure
    idxLeafModels = find(obj.leafModels);
    localLossFunctionValue = calcLocalLossFunction(obj, obj.unscaledOutput, obj.outputModel , obj.phi(:,idxLeafModels), obj.dataWeighting);
    for k = 1:numel(idxLeafModels)
        obj.localModels(idxLeafModels(k)).localLossFunctionValue = localLossFunctionValue(k);
    end
    % Get all local loss function values (loop over all leafs that are allowed for further splitting)
    localLFV = cell2mat(arrayfun(@(locobj) locobj.localLossFunctionValue, obj.localModels(idxAllowedLeafs), 'UniformOutput', false));
end


% Find maximum of all LMs that are allowed for further splitting
[~,index] = max(localLFV);

% Get the index of the model within the active models
realIdx = find(idxAllowedLeafs);
worstLMIdx = realIdx(index);

end
