% Copyright (C) 2013-2014 Czech Technical University in Prague
%
% Authors:
%     - Carlos Jenkins <carlos@jenkins.co.cr>
%
% This document contains proprietary information belonging to Czech
% Technical University in Prague. Passing on and copying of this
% document, and communication of its contents is not permitted
% without prior written authorization.
%
% File : compile_blocks.m
% Abstract:
%     Compile all the C-MEX S-Function in current folder.
%
% References:
%     http://www.mathworks.com/help/matlab/ref/mex.html
%     http://www.mathworks.com/help/matlab/matlab_external/custom-building-mex-files.html


function compile_blocks()

    % Options:
    % -g        Create a binary MEX-file containing additional symbolic
    %           information for use in debugging. This option disables the mex
    %           default behavior of optimizing built object code
    %           (see the -O option).
    % -v        Verbose mode. Print the values for important internal variables
    %           after the options file is processed and all command-line
    %           arguments are considered. Prints each compile step and final
    %           link step fully evaluated.
    % options = '-v -g';
    options = '';
    mex = fullfile(matlabroot(), 'bin', 'mex');
    sources = dir('sfunction_*.c');

    for i = sources'
        local_opts = options;
        if strcmp(i.name, 'sfunction_canreceive.c') || ...
           strcmp(i.name, 'sfunction_cantransmit.c'),
            local_opts = [local_opts ' ' ...
                '-I' matlabroot  '/toolbox/shared/can/src/scanutil ' ...
		'-I' matlabroot  '/toolbox/rtw/targets/common/can/datatypes ' ...
                matlabroot '/toolbox/rtw/targets/common/can/datatypes/sfun_can_util.c '...
                matlabroot '/toolbox/rtw/targets/common/can/datatypes/can_msg.c'];
        end
        command = [mex ' ' i.name ' ' local_opts];
        disp(command);
        [status, result] = system(command);
        if status ~= 0,
            disp(result)
            throw(MException('rpp:compile_block_failure', [i.name, ' failed to compile']))
        end
    end

end
