function history = writeHistory(history,LMobj,tStart)
% WRITEHISTORY is called after each iteration to write all necessary data
% into the history
%
% call the function like this: obj.history = writeHistory(obj.history,obj,tStart);
%
% ATTENTION: history is the history object! LMobj is the local model network!

% LMNtool - Local Model Network Toolbox
% Tobias Ebert, 24-April-2012
% Institute of Mechanics & Automatic Control, University of Siegen, Germany
% Copyright (c) 2012 by Prof. Dr.-Ing. Oliver Nelles

% increase iteration by one
iter = history.iteration+1;

% initialise iteration number
history.iteration = iter;

% set global loss function
if numel(history.globalLossFunction) < iter
    if isprop(LMobj,'outputModel') && ~isempty(LMobj.outputModel)
        history.globalLossFunction(iter) = ...
            calcGlobalLossFunction(LMobj, LMobj.unscaledOutput, LMobj.outputModel, LMobj.dataWeighting, LMobj.outputWeighting);
    else
        history.globalLossFunction(iter) = ...
            calcGlobalLossFunction(LMobj, LMobj.unscaledOutput, LMobj.calculateModelOutput, LMobj.dataWeighting, LMobj.outputWeighting);
    end
end

% set validation Data loss function
if ~isempty(LMobj.validationInput) &&  ~isempty(LMobj.validationOutput)
    history.validationDataLossFunction(iter) = calcGlobalLossFunction(...
        LMobj, LMobj.validationOutput, ...
        LMobj.calculateModelOutput(LMobj.validationInput,LMobj.validationOutput),...
        [], LMobj.outputWeighting);
end

% set test Data loss function
if ~isempty(LMobj.testInput) &&  ~isempty(LMobj.testOutput)
    history.testDataLossFunction(iter) = calcGlobalLossFunction(...
        LMobj, LMobj.testOutput, ...
        LMobj.calculateModelOutput(LMobj.testInput,LMobj.testOutput),...
        [], LMobj.outputWeighting);
end

% penalty loss function and current number of parameters
[penaltyLossFunction, numberOfAllParameters, CVScore, nEff, AICc] = LMobj.calcPenaltyLossFunction;
history.penaltyLossFunction(iter) = penaltyLossFunction;
history.AICc(iter) = AICc;
history.currentNumberOfParameters(iter) = numberOfAllParameters;
if ~isempty(CVScore)
    history.CVLossFunction(iter) = CVScore;
end
if ~isempty(nEff)
    history.currentNumberOfEffParameters(iter) = nEff;
end

% Store current number of LMs in history
history.currentNumberOfLMs(iter) = sum(LMobj.leafModels);

% set state of leaf models in history
history.leafModelIter{iter} = LMobj.leafModels;

% set training time
if exist('tStart','var')
    history.trainingTime(iter) = toc(tStart);
else
    history.trainingTime(iter) = NaN;
end

end