function varargout = systemCommand(command, system, varargin)
%

%   Copyright 2011-2016 The MathWorks, Inc.

    if ~any(strcmp(command,{'close_system','new_system','load_system', 'Sldv.silent_load_helper'}))
        error(message('Sldv:utils:systemCommand:WrongCommand'));
    end
    
    oldRoot = bdroot;
    cursys = get_param(0,'CurrentSystem');
    if ~isempty(cursys)
        curblk = get_param(cursys, 'CurrentBlock');
    else
        curblk = '';
    end
    
    if ~ischar(system)
        systemName = get_param(system,'Name');
    else
        [~,systemName] = fileparts(system);
    end
    
    commandError = [];
    try
        [varargout{1:nargout}] = feval(command, system, varargin{1:end});
    catch Mex 
        commandError = Mex;
    end
    
    try
        if ~isempty(curblk) && ~strcmp(command,'close_system') && ...
                ~strcmp(curblk,get_param(cursys, 'CurrentBlock')) && ...
                ~strcmp(get_param(cursys,'Lock'),'on')
            set_param(cursys, 'CurrentBlock', curblk);
        end
        if ~isempty(cursys) && ...
                ~(strcmp(command,'close_system') && strcmp(systemName,cursys))
            set_param(0,'CurrentSystem',cursys);    
            bdroot(oldRoot); 
        end    
    catch Mex      %#ok<NASGU>
    end
    
    if ~isempty(commandError)
        rethrow(commandError);
    end
end
