function [errorCode, messageStr] = mbuild_helper(varargin)
%MBUILD_HELPER is a helper function that contains the code that MBUILD.M
%   (an autogenerated file) executes.  It sets up the inputs to call mex.
%
%   For information on how to use MBUILD see MBUILD help by typing "help
%   mbuild" or "mbuild -h".

%   $Date $
% Copyright 1984-2016 The MathWorks, Inc.

errMsg = '';
dashg = true;

try
    for n = 1:numel(varargin)
        validateattributes(varargin{n},{'char','string'}, ...
            {'scalartext'},'mbuild','',n)
        varargin{n} = char(varargin{n});
        
        if contains(varargin{n},' ')
            varargin{n} = [ '"' varargin{n} '"' ];
        end
        
        if (strcmp(varargin{n},'-h') || strcmp(varargin{n},'-help'))
            displayHelp;
            return;
        end
        
        if dashg && strcmp(computer,'MACI64') && strcmp(varargin{n},'-g')
            CMDLINE250 = 'CMDLINE250=xcrun -sdk macosx$SDKVER dsymutil "$EXEDIR$EXENAME.app/Contents/MacOS/$EXENAME"';
            varargin = [{CMDLINE250},varargin]; %#ok<AGROW>
            dashg = false;
        end        
    end
    
    % When mbuild -setup -client mbuild_com is executed, the
    % Compiler for COM components is selected
    if(~isempty(find(strcmp(varargin,'-setup'),1)) && ...
            ~isempty(find(strcmp(varargin,'mbuild_com'),1)) && ...
            isempty(find(strcmp(varargin,'c++'),1)) )
        varargin = [varargin,{'c++'}];
    end
	
    varargin = [{'-client','mbuild'},varargin];
    errCode = mex(varargin{:});    
catch ex
    errMsg = ex.message;
    errCode = 1;
end

if nargout > 0
    if nargout == 2
        messageStr = errMsg;
    end
    errorCode = errCode;
elseif errCode ~= 0
    error(message('Compiler:mbuild_helper:genericFailure',errMsg))
end


%%%%%%%%%%%%%%%%%%%%
%%% SUBFUNCTIONS %%%
%%%%%%%%%%%%%%%%%%%%

% Display MBUILD Help
function displayHelp

if ispc
    [errCode, result] = compilerDos(['"' matlabroot '\bin\mbuild.bat' '"' ' -h']);
else
    [errCode, result] = unix(['"' matlabroot '/bin/mbuild' '"' ' -h']);   
end

if(errCode)
   error(message('Compiler:mbuild_helper:unableToDisplayHelp'));
else
   disp(result);
end
