%% Remove Initialization Code from Root-Level Inports and Outports Set to Zero
% This example shows how to remove initialization code from root-level
% inports and outports set to zero. 
% 
%
%   Copyright 2017 The MathWorks, Inc.
%% Example Model
% In the model <matlab:rtwdemo_rootlevel_zero_initialization rtwdemo_rootlevel_zero_initialization>, all of the input
% and output signals have a numeric value of zero. Because signals |sig1| and |sig2|
% have data types |int16| and |Boolean|, respectively, and all of the
% output signals have data type |double|, these signals also have initial
% values of bitwise zero. The signals have an integer bit pattern of |0|,
% meaning that all bits are off. Signals |sig1_b| and |sig2_b| have a
% fixed-point data type with bias, so their initial value is not bitwise
% zero.
model = 'rtwdemo_rootlevel_zero_initialization';
open_system(model);

%% Generate Code
% In your system temporary folder, create a temporary folder for the
% build and inspection process.
currentDir = pwd;
[~,cgDir] = rtwdemodir();

%%
% Build the model by using Embedded Coder.
set_param(model, 'ZeroExternalMemoryAtStartup','on');
evalc('rtwbuild(model)');

%%  
% These lines of |rtwdemo_rootlevel_zero_initialization.c| code show the initialization of root-level inports and outports
% without the optimization. The four input signals are individually
% initialized as global variables. The four output signals are members of a
% global structure that the |memset| function initializes to bitwise zero.
cfile = fullfile(cgDir,'rtwdemo_rootlevel_zero_initialization_ert_rtw',...
    'rtwdemo_rootlevel_zero_initialization.c');
rtwdemodbtype(cfile, 'rtwdemo_rootlevel_zero_initialization_initialize',...
    'trailer for generated code', 1, 0);

%% Enable Optimization
% # Open the Configuration Parameters dialog box.  
% # On the *Optimization* pane, select 
%   *Remove root level I/O zero initialization*.
%
% Alternatively, use the command-line API to enable the optimization:
 set_param(model, 'ZeroExternalMemoryAtStartup','off');

%% Generate Code with Optimization 
% The optimized code does not contain initialization code for the input
% signals |sig1|, |sig2|, and the four output signals because their initial
% values are bitwise zero.
% 
% Build the model.
evalc('rtwbuild(model)');

%%
% Here is the |rtwdemo_rootlevel_zero_initialization.c| optimized code in the initialization function.
cfile = fullfile(cgDir,'rtwdemo_rootlevel_zero_initialization_ert_rtw',...
    'rtwdemo_rootlevel_zero_initialization.c');
rtwdemodbtype(cfile, 'rtwdemo_rootlevel_zero_initialization_initialize',...
    'trailer for generated code', 1, 0);

%%
% Close the model and the code generation report.
bdclose(model)
rtwdemoclean;
cd(currentDir)
