% 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
% Abstract:
%     Generates library rpp_lib.slx for targets
%
% 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()
    blocks = rpp_get_blocks();
	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');
    save_system('rpp_lib');
	close_system('rpp_lib.slx', 1);
end
