function obj = estimateModelGlobal(obj,iteration)
% ESTIMATEMODELGLOBAL recalculates the model parameters using a global
% estimation. The number of effective parameters rises, but the
% regularization-effect gets lost.
%
%   obj = estimateModelGlobal(obj,iteration)
%
% Output:
%   obj:        object      LOLIMOT object containing all relevant net
%                           and data set information and variables.
%
% INPUT:
%   obj:        object      LOLIMOT object containing all relevant net
%                           and data set information and variables.
%   iteration:  (1 x 1)     Index of the iteration expressing the
%                           number of local models to be used and their
%                           certain partition.
%
%
% LoLiMoT - Nonlinear System Identification Toolbox
% Torsten Fischer, 08-December-2011
% Institute of Mechanics & Automatic Control, University of Siegen, Germany
% Copyright (c) 2012 by Prof. Dr.-Ing. Oliver Nelles


% Check if an certain iteration should be used
if exist('iteration','var')
    if iteration > numel(obj.history.leafModelIter)
        % Iteration number too high: take last calculated net
        obj.leafModels = obj.history.leafModelIter{end};
    else
        % Change leafs to the wanted iteration/amount
        obj.leafModels = obj.history.leafModelIter{iteration};
    end
end

% Calculate the validities of all leafs/used local models
validityFunctionValue = obj.calculateVFV(obj.MSFValue(obj.leafModels));

% Get the indicies of the leaf models
idxLeafModels = find(obj.leafModels);

% Calculate all coefficients at the same time (global estimation)
coeff = estimateParametersGlobal(obj, obj.xRegressor, obj.output, cell2mat(validityFunctionValue), [], obj.dataWeighting);

% Add the coefficients to the right local models
for k = 1:length(idxLeafModels)
    obj.localModels(idxLeafModels(k)).parameter = coeff{k};
end

% Calculate model output
obj.outputModel = calculateModelOutput(obj);

% 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

% Update the history object
obj.history = writeHistory(obj.history,obj);

end