function mcr_build(srcpath, mainfunc, threadingmode)

%===============================================================================
% MATLAB MCR EXAMPLE: BUILD CODE
%
% This function calls Matlab Compiler to build an executable from user code.
%
% INPUT
%   srcpath ............ base path to sources (m-files)
%   mainfunc ........... name of main M-function to be compiled
%                        -> file name of function only (no path)
%                        -> without extension ".m"
%                        -> according m-file must be located in srcpath
%   threadingmode ...... set multithreading mode (optional)
%                        -> 'disableThreading', 'enableThreading' (default)
%===============================================================================

%===============================================================================
% Construct basic compiler command.
%===============================================================================
if nargin < 3 || (nargin==3) && strcmp(lower(threadingmode), 'enablethreading')
    cmd = ['mcc' ...
            ' -m' ...
            ' -R -nodisplay' ...
            ' -o ' mainfunc ...
            ' ' srcpath '/' mainfunc '.m'];
elseif (nargin==3) && strcmp(lower(threadingmode), 'disablethreading')
    cmd = ['mcc' ...
            ' -m' ...
            ' -R -nodisplay' ...
            ' -R -singleCompThread' ...
            ' -o ' mainfunc ...
            ' ' srcpath '/' mainfunc '.m'];
end

%===============================================================================
% Find dependencies and add them to the command.
% -> all subdirectories in srcpath are assumed to be dependencies
%===============================================================================
fcont = dir(srcpath);
for d = fcont'
    if d.isdir && ~strcmp(d.name,'.') && ~strcmp(d.name,'..')
        cmd = [cmd ' -a ' fullfile(srcpath, d.name)];
    end
end
cmd = strrep(cmd, '//', '/');

%===============================================================================
% Compile!
%===============================================================================
fprintf('Compiling %s via following mcc-command:\n\t%s\n\n', mainfunc, cmd);
eval(cmd);
movefile(mainfunc, ['./bin/' mainfunc '.exe']);