% RPP_GENERATE_LIB  Generates rpp_lib.slx library for the current target.

% Copyright (C) 2013-2015 Czech Technical University in Prague
%
% Authors:
%     - Michal Horn <hornmich@fel.cvut.cz>
%
% 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_generate_lib.m
%
% References:
%     http://www.mathworks.com/help/matlab/ref/mex.html
%     http://www.mathworks.com/help/matlab/matlab_external/custom-building-mex-files.html

function rpp_generate_lib()
    target = rpp_get_target();
    blocks = {};
    if strcmp(target, 'rm48_hdk') || strcmp(target, 'tms570_hdk'),
        blocks = {
                'rpp_can_rx',
                'rpp_can_setup',
                'rpp_can_tx',
                'rpp_gio_in',
                'rpp_gio_out',
                'rpp_hdk_ain',
                'rpp_overrun',
                'rpp_sci_cfg',
                'rpp_sci_printf',
                'rpp_sci_rx',
                'rpp_sci_tx'
                 };
    end

	d = fullfile(getpref('rpp', 'TargetRoot'), '..', 'blocks');
	cd(d)

    try,
        load_system('rpp_lib.slx');
    catch ME
        new_system('rpp_lib', 'Library');
    end
	set_param('rpp_lib', 'Lock', 'off');
	oldBlocks = find_system('rpp_lib', 'Type', 'block');
	disp('Removing old blocks:');
	for j=1:length(oldBlocks),
		disp(['    ', oldBlocks{j}]);
		delete_block(oldBlocks{j});
	end
	disp('Adding new blocks:');
	for j=1:length(blocks),
		blockFilePath=[blocks{j}, '.slx'];
		disp(['    from: ', blockFilePath, ':']);
		load_system(blockFilePath)
		newBlocks = find_system(blocks{j}, 'Type', 'block');
		for k=1:length(newBlocks),
			[tok, blockName] = strtok(newBlocks{k}, '/');
			blockName = ['rpp_lib', blockName];
			disp(['        ', newBlocks{k}, ' as ', blockName]);
			add_block(newBlocks{k}, blockName);
		end
		close_system(blockFilePath, 0);
	end
	disp(['Closing and saving file ', 'rpp_lib.slx']);
	set_param('rpp_lib', 'Lock', 'on');
	close_system('rpp_lib.slx', 1);
end
