% Copyright (C) 2013 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 : rpp_download.m
% Abstract:
%     Code download utility for Simulink RPP Target.
%
%     This function is optionally executed at the end of the build process
%     if it is successful and the user selected "Download compiled binary to
%     RPP" option on the build configuration panel. This function calls
%     loadti.sh script with the generated binary and using configuration for
%     the XDS100v2 JTAG Emulators.
%
% References:
%     loadti utility wiki at http://processors.wiki.ti.com/index.php/Loadti
%     Readme file in <cssroot>/ccs_base/scripting/examples/loadti/readme.txt


function rpp_download(modelName, buildDirectory)

    CCSRoot    = getpref('rpp', 'CCSRoot');
    RppLibRoot = getpref('rpp', 'RppLibRoot');

    %TODO: parse the EXE_FILE_EXT from target_tools.mk
    outfile     = fullfile(buildDirectory, [modelName, '.out']);
    downloadLog = fullfile(buildDirectory, 'download.log');

    if isunix

        disp(['### Downloading ', modelName, ' to RPP board...']);

        % -a,   --async-run             Run the specified executable and return without halting
        % -r,   --reset                 Reset target before run
        % -c,   --cfg-file=CONFIG_FILE  Target setup config file
        command = [...
            'CCS_SCRIPTING="' CCSRoot '/ccs_base/scripting/" ' ...
            '"' RppLibRoot '/../loadti/loadti.sh" -a -r ' ...
            '-c "', RppLibRoot, '/rpp/TMS570LS3137.ccxml" ', ...
            '"', outfile, ...
            '" 2> "', downloadLog, '"'];
        disp('### Running downloader script:');
        disp(command);
        system(command);

        disp(['Done. <a href="matlab:open(''', downloadLog, ''')">Open download log.</a>']);

    else
        disp(['### Sorry code download is available for UNIX systems only.']);
        disp(['###     -> Add support for non UNIX systems in <targetroot>/rpp/rpp_download.m file.']);
    end
end
