function [result pbeDefinition] = loadPbeResult(caseName)
% load data from executed population balance
%
% Syntax: [result pbeDefinition] = loadResultPbe(caseName)
%
% The case from the data folder is loaded (result) and returned including
%   its original definition (pbeDefinition).
%
% See also: executeCasePbe, solvePbe

% The elk-library: convex geometry applied to crystallization modeling.
%   Copyright (C) 2012 Alexander Reinhold
%
% This program is free software: you can redistribute it and/or modify it 
%   under the terms of the GNU General Public License as published by the 
%   Free Software Foundation, either version 3 of the License, or (at your 
%   option) any later version.
%
% This program is distributed in the hope that it will be useful, but 
%   WITHOUT ANY WARRANTY; without even the implied warranty of 
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
%   General Public License for more details.
%
% You should have received a copy of the GNU General Public License along 
%   with this program.  If not, see <http://www.gnu.org/licenses/>.

%% input handling
if ~exist('caseName', 'var')
    caseName = [];
end
% thats my path:
myPath = fileparts(which(mfilename));
% starting path
currentPath = cd;

%% database handling
if nargout == 0
    obtainData(caseName, 'database', [myPath filesep 'data'], 'type', 'mat');
else
    result = obtainData(caseName, ...
        'database', [myPath filesep 'data'], 'type', 'mat');
%     if isfield(result, 'result')
        pbeDefStored = result.pbeDefinition;
        pbeDefinitionString = result.pbeDefinitionString;
        result = result.result;
        pbeDefStored = convertStringToFunctionPbe(pbeDefStored);
%     else
%         pbeDefStored = result;
%     end
    
    % write generating file
    cd([myPath filesep 'database'])
    fileHandle = fopen('tmpPbeDefinition.m', 'w');
    fprintf(fileHandle, '%s', pbeDefinitionString);
    fclose(fileHandle);
    % ensure it is in scope for matlab
    rehash
    % and call it
    pbeDefinition = tmpPbeDefinition;
    % remove it again
%     delete('tmpPbeDefinition.m')
    cd(currentPath)
    % Result: all anonymuous functions in tmpPbeDefinition can be called
    %   again.
    
    % ensure extra fields in pbeDef from solver are present
    pbeDefinition = mergeStruct(pbeDefinition, pbeDefStored);
    
    % ensure option struct is complete
    pbeDefinition.optionStruct = mergeStruct(pbeDefStored.optionStruct, ...
        pbeDefinition.optionStruct);
    
    
end