% 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 : rpp_download.m
% Abstract:
%     Code download utility for Simulink RPP Target.
%
%     This function is executed by rpp_make_rtw_hook.m only if the build process
%     finished successfully and RPP_DOWNLOAD is set to TRUE. The RPP_DOWNLOAD option
%     is controlled by "Download to RPP board" option in RPP code generation options.
%
%     Avoid executing this function with Code Composer Studio running on background.
%
% Parameters:
%     use_openocd - When set to TRUE, an OpenOCD will be used for the code
%                 download. This tool is available only for Unix based systems.
%                 When set to FALSE, a Texas Instruments Loader will be used.
%                 for the code download. The TI tool is available for Unix based
%                 systems and Windows.
%                 This parameter is controled by "Use OpenOCD to download the compiled binary"
%                 option in RPP code generation options.
%     use_sdram - When set to TRUE, the code will be downloaded into SDRAM. This option
%                 requires a base code for the MPU, EMIF, POM and SDRAM configuration to
%                 be present in the device Flash memory. The presence of the code is not
%                 verified.
%                 When set to FALSE, the code will be downloaded into the Flash memory.
%                 This option is usefull for debugging as the Flash memory has very limited
%                 number of rewrites.
%                 NOTE: The code execution may be slower from the SDRAM than from the Flash.
%                 NOTE: This function is not yet implemented.
%                 This parameter is controlled by "Download compiled binary to SDRAM"
%                 option in RPP code generation options.
%
% References:
%     loadti utility wiki at http://processors.wiki.ti.com/index.php/Loadti
%     Readme file in <cssroot>/ccs_base/scripting/examples/loadti/readme.txt
%     OpenOCD wiki at https://rtime.felk.cvut.cz/hw/index.php/TMS570LS3137#OpenOCD_setup_and_Flashing

function rpp_download(modelName, buildDirectory, use_openocd, use_sdram)
	RppLibRoot = getpref('rpp', 'RppLibRoot');
	CCSRoot    = getpref('rpp', 'CCSRoot');
	
	%TODO: parse the EXE_FILE_EXT from target_tools.mk
	outfile     = fullfile(buildDirectory, [modelName, '.out']);
	downloadLog = fullfile(buildDirectory, 'download.log');

	if use_openocd
		if use_sdram
			disp(['### Sorry, Downloading to the SDRAM is not yet implemented.'])
			disp(['###     -> Uncheck the option "Download compiled binary to SDRAM" (set use_openocd to false) to download the code to the Flash memory.'])
		else
			if isunix
				command = [...
					RppLibRoot '/../loadopenocd/loadopenocd.sh -d flash -b -s ' ...
					, outfile, ' 2> ' , downloadLog ];
				disp('### Running downloader script:');
				disp(command);
				status = system(command);
				if status ~= 0,
					throw(MException('rpp:targetDlErr', ['Failed to download ' modelName ' to the target']))
				end
				disp(['Done. <a href="matlab:open(''', downloadLog, ''')">Open download log.</a>']);			
			else
				disp(['### Sorry code download via OpenOCD is available for UNIX systems only. Uncheck the option']);
				disp(['###     -> Uncheck the option "Use OpenOCD to download the compiled binary" to use Ti downloader, which is functional under Windows.']);
			end
		end
	else
		if use_sdram
			disp(['### Sorry, Downloading to the SDRAM is not yet implemented.'])
			disp(['###     -> Uncheck the option "Download compiled binary to SDRAM" (set use_sdram to false) to download the code to the Flash memory.'])
        else
            disp(['### Downloading ', modelName, ' to RPP board...']);
			if isunix
				% -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" -r ' ...
					'-c "', RppLibRoot, '/rpp/TMS570LS3137.ccxml" ', ...
					'"', outfile, ...
					'" 2> "', downloadLog, '"'];
			else
				% -r,   --reset                 Reset target before run
				% -c,   --cfg-file=CONFIG_FILE  Target setup config file
				command = [...
					'set CCS_SCRIPTING="' CCSRoot '\..\..\ccs_base\scripting\" && ' ...
					'"' RppLibRoot '\..\loadti\loadti.bat" -r ' ...
					'-c "', RppLibRoot, '\rpp\TMS570LS3137.ccxml" ', ...
					'"', outfile];
            end
            disp('### Running downloader script:');
            disp(command);
            status = system(command, '-echo');
            if status ~= 0,
                throw(MException('rpp:targetDlErr', ['Failed to download ' modelName ' to the target']))
            end
            disp(['Done. <a href="matlab:open(''', downloadLog, ''')">Open download log.</a>']);    
        end
	end

end
