function [result pbeDefinition] = executePbeCase(caseName)
% execute a case from the database
%
% Syntax: result = executeCase(caseName)
%
% The case from the database folder is executed and the results are stored 
%   in the data folder for further analysis.
%
% See also: loadCasePbe, 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));

%% database handling
if isempty(caseName) || strcmpi(caseName, 'init')
    if nargout == 0
        obtainData(caseName)
    else
        result = obtainData(caseName);
    end
    return
else
    pbeDefinition = obtainData(caseName);
end

%% execute solver
[result pbeDefinition] = solvePbe(pbeDefinition);

%% save data
% make pbeDefinition available by saving the whole file to string
pbeDefinitionString = fileread([myPath filesep 'database' filesep caseName '.m']);
% make functions storable by conversion to strings
pbeDefinition = convertFunctionToStringPbe(pbeDefinition);

% save file
save([myPath filesep 'data' filesep caseName '.mat'], 'result', ...
    'pbeDefinition', 'pbeDefinitionString', '-v7.3');
% update index file
dump = obtainData('init', 'database', [myPath filesep 'data'], 'type', 'mat');

%% output
if nargout == 0
    clear result
end