function worstLMIdx = findWorstLM(obj)
% FINDWORSTLM finds the index of the worst performing local model.
%
% worstLMIdx = findWorstLM(obj)
%
% INPUT:
%   obj:         object     LOLIMOT object containing all relevant net
%                           and data set information and variables.
%
% OUTPUT:
%   worstLMIdx:  (1 x 1)    Index of the worst performing local model;
%                           highest local loss function value.
%
%
% LoLiMoT - Nonlinear System Identification Toolbox
% Tobias Ebert, 19-October-2011
% 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);

% Get all local loss function values

% if ~isempty(regexp(version,'R2010a','once'))
%     % workaround for R2010a
%     localLFV = cell2mat(cellfun(@(locobj) locobj.localLossFunctionValue,{obj.localModels(idxAllowedLeafs)},'UniformOutput',false));
% else
%     localLFV = cell2mat(arrayfun(@(locobj) locobj.localLossFunctionValue,obj.localModels(idxAllowedLeafs),'UniformOutput',false));
% end

localLFV = [obj.localModels(idxAllowedLeafs).localLossFunctionValue];

% Check if 
if isempty(localLFV)
    % Evaluate new loss function values and update structure
    % Indicies of the active models
    idxLeafModels = find(obj.leafModels);
    
    % Get all active gaussians and normalize them
    validityFunctionValue = obj.calculateVFV(obj.MSFValue(obj.leafModels));
    
    
    % Calculate the local loss function values for all leaf models
    localLossFunctionValue = calcLocalLossFunction(obj, obj.unscaledOutput, obj.outputModel , cell2mat(validityFunctionValue), obj.dataWeighting, obj.outputWeighting);
    for k = 1:numel(idxLeafModels)
        % Allocate the right local loss function value to each local model
        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 = [obj.localModels(idxAllowedLeafs).localLossFunctionValue];
end

% Find minimum
[~,index] = max(localLFV);

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

end

