function port = adasblocks_utilUpdateOutport(blk,fromblockname,AvailableBlocks,...
                                              type_out_mask,type_out_block,...
                                              index,name,port,fromport)
% This is a utility function refreshes optional block ourports in the
% Vehicle Path Planner (VPP) block dialog. When the ourport is turned off,
% a terminator block is used as the destination.
% 
% Inputs:
%   blk:                the masked subsystem where the outport is added
%   fromblockname:      which block the outport connects to
%   AvailableBlocks:    all the blocks inside masked subsystem
%   type_in_mask:       all optional outports demands in the mask dialog
%   type_in_block:      all optional outports in the masked subsystem
%   index:              index in the list of all optional outports
%   name:               name of the outports
%   port:               port number in the masked subsystem
%   fromport:           port number of the "fromblock" that it connects to

%   Copyright 2022 The MathWorks, Inc.

if type_out_mask(index)
    if ~type_out_block(index)
        add_outport(blk,name,port,[fromblockname '/' num2str(fromport)]);
    end
    port = port + 1;
else
    if type_out_block(index)
        if ismember(name,AvailableBlocks)
            delete_outport(blk,name,[fromblockname '/' num2str(fromport)]);
        end
    end
end

% Local functions
function add_outport(blk,name,port,fromport)
outportblk = [blk '/' name];
terminatorblk = [blk '/' name '_terminator']; 
delete_line(blk,fromport,[name '_terminator/1']);
position = get_param(terminatorblk,'position');
delete_block(terminatorblk);
add_block('built-in/Outport',outportblk);
add_line(blk,fromport,[name '/1']);
set_param(outportblk,'position',position,'port',num2str(port));

function delete_outport(blk,name,fromport)
outportblk = [blk '/' name];
terminatorblk = [blk '/' name '_terminator']; 
delete_line(blk,fromport,[name '/1']);
position = get_param(outportblk,'position');
delete_block(outportblk);
add_block('built-in/Terminator',terminatorblk);
add_line(blk,fromport,[name '_terminator/1']);
set_param(terminatorblk,'position',position);
