function callSystemFunction(command, varargin)
% try to execute a system function
%
% This function supports calls of system functions with several comfort
%   options that can be provided.
%
% systemFunction(.., 'logfile', logfile) writes the output in a logfile 
%   when a nonempty string is provided. Default: ''
%
% systemFunction(.., 'resetLog', 1) overwrites logfile. Default: 0
%
% systemFunction(.., 'error type') if the evaluation of the command fails,
%   an error is thrown with that type. Default: 'mdt:systemFunction'
%
% systemFunction(.., 'error message') if the evaluation of the command 
%   fails, an error is thrown with that message. Default: 'call of system 
%   function returned an error'
%
% systemFunction(.., 'error flush log', 0) if the evaluation of the command 
%   fails the logfile is typed to the command window before the error is
%   called. This option let's you switch off this behavior. Default: 1
%

% MDT: MATLAB developement tools
%   Copyright (C) 2012 Alexander Reinhold
%
% This program is free software: you can redistribute it and/or modify it 
%   under the terms of the GNU Lesser 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 
%   Lesser General Public License for more details.
%
% You should have received a copy of the GNU Lesser General Public License 
%   along with this program.  If not, see <http://www.gnu.org/licenses/>.

%% map options
[resetLog, logFile, errorType, errorMessage, errorFlush] = mapOption(varargin, ...
    'reset logfile', 0, ...
    'logfile', '', ...
    'error type', 'mdt:systemFunction', ...
    'error message', 'call of system function returned an error', ...
    'error flush log', 1);

if resetLog == 1
    streamLog = ' > ';
else
    streamLog = ' >> ';
end

if ~isempty(logFile)
   command = [command streamLog logFile];
end

[status, result] = system(command);
if status > 0
    if errorFlush && ~isempty(logFile)
        type(logFile);
    end
    error(errorType, errorMessage);
end
