function port = utilUpdateInport(blk,AvailableBlocks,type_in_mask,type_in_block,index,name,port)
% Utility function refreshes optional block inports.  When the inport is
% turned off, a constant block is used as the source.
%
%   blk:                the masked subsystem where the inport is added
%   AvailableBlocks:    all the blocks inside masked subsystem
%   type_in_mask:       all optional inports demands in the mask dialog
%   type_in_block:      all optional inports in the masked subsystem
%   index:              index in the list of all optional inports
%   name:               name of the inport
%   port:               port number in the masked subsystem

%   Author: A. Zimmerman
%   Copyright 2016-2020 The MathWorks, Inc.

StaticName = ['Ground_' name];
StaticBlockType = 'built-in/Ground';
PortName = name;
isNewPort = type_in_mask(index);
isExistPort = type_in_block(index);
sys = getfullname(blk);

inportblk = [sys '/' name];
groundblk = [sys '/' StaticName];

% Add/Delete Ports
if isNewPort  % Add inport
    if ~isExistPort
        position = get_param(groundblk,'position');
        delete_block(groundblk);
        add_block('built-in/Inport',inportblk);
        set_param(inportblk,'position',position,'port',num2str(port));
    end
    port = port + 1;
else % Delete Inport
    if isExistPort
        if ismember(PortName,AvailableBlocks)
            position = get_param(inportblk,'position');
            delete_block(inportblk);
            add_block(StaticBlockType,groundblk, 'Position', position);
        end
    end
end
