function [newPoints dMin] = DoEGenerateNewData(obj, worstLM)
% DOEGENERATENEWDATA generates space-filling data samples in the worst local model region.
%
%
% [newPoints] = DoEGenerateNewData(obj, worstLM)
%
%
% INPUT
%
%   obj:        object   HILOMOTDOE object containing all relevant properties and methods.
%   worstLM:    1 x 1    Index of LM with the largest local loss function value.
%
%
% OUTPUT
%
%   newPoints:  ? x p    New point(s) for measurement (query points).
%
%
% HiLoMoTDoE - Nonlinear System Identification Toolbox for Design of Experiments
% Benjamin Hartmann, 05-April-2012
% Institute of Mechanics & Automatic Control, University of Siegen, Germany
% Copyright (c) 2012 by Prof. Dr.-Ing. Oliver Nelles


% For initialization
if isempty(worstLM)
    worstLM = 1;
end

% Initialize new net, data set and some constants
netCrisp = obj.LMNObject;

% Generate crisp transitions of the validity functions
netCrisp.smoothness = 1e-6;  % Very low smoothness for hard switching between LMs

% Load candidate points from existing data set and normalize
[candidatePoints,MaxVal,MinVal] = obj.DoEScaleData(obj.candidatePoints);

% Evaluate phi values in worstLM for all random points
phi = netCrisp.calculatePhi(candidatePoints, worstLM);

% Separate all existing points of the investigated LM
idx = (phi>0.5);
N = sum(idx); % Number of candidate points in current LM
if N < 1 % The number of candidate points in one LM must be sufficient
    %warning('hilomotDoE:DoEGenerateNewData','No candidate points existing with validity over 0.5: Switch to next worst LM.')
    worstLoss = sort(cell2mat({netCrisp.localModels.localLossFunctionValue}));
    count = 1;
    while N<1
        if count >= size(worstLoss,2)
            return
        end
        p   = find(worstLoss == worstLoss(end-count));
        phi = netCrisp.calculatePhi(candidatePoints, p);
        idx = (phi>0.5);
        N = sum(idx); % Number of candidate points in current LM
        count = count + 1;
    end
end
candidatePointsLM = candidatePoints(idx,:);

% Generate new homogeneous distributed data samples in worst LM.
numberOfNewPoints = 1;
existingPoints    = obj.DoEScaleData(obj.inputTarget,MaxVal,MinVal,'f');
[newPoints dMin]  = obj.DoEPMCPoint(numberOfNewPoints, existingPoints, candidatePointsLM);

end