function port = adasblocks_utilUpdateInport(blk,toblockname,AvailableBlocks,type_in_mask,type_in_block,index,name,port,toport,varname,DataType)
% Utility function refreshes optional block inports in the Adaptive Cruise
% Control (ACC) System and Lane Keeping Assist System (LKA) block dialog.
% When the inport is turned off, a constant block is used as the source.
%
% Four optional inports for ACC block:
%   maximum acceleration amax
%   maximum deceleration amin
%   tracking external acceleration atrack
%   enabling optimization optsgn
%
% Four optional inports for LKA block plus state-space matrics (A,B,C):
%   maximum steering umax
%   minimum steering umin
%   tracking external utrack
%   enabling optimization optsgn
% 
% Inputs:
%   blk:                the masked subsystem where the inport is added
%   toblockname:        which block the inport connects to
%   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
%   toport:             port number of the "toblock" that it connects to
%   varname:            value set in the constant block 

%   Author: Meng Xia, Rong Chen
%   Copyright 2017-2018 The MathWorks, Inc.

if type_in_mask(index)
    if ~type_in_block(index)
        add_inport(blk,name,port,[toblockname '/' num2str(toport)]);
    end
    port = port + 1;
else
    if type_in_block(index)
        if ismember(name,AvailableBlocks)
            delete_inport(blk,name,[toblockname '/' num2str(toport)],varname,DataType);
        end
    end
end

    


function add_inport(blk,name,port,toport)
inportblk = [blk '/' name];
constantblk = [blk '/' name ' constant']; 
delete_line(blk,[name ' constant/1'],toport);
position = get_param(constantblk,'position');
delete_block(constantblk);
add_block('built-in/Inport',inportblk);
add_line(blk,[name '/1'],toport);
set_param(inportblk,'position',position,'port',num2str(port));

function delete_inport(blk,name,toport,varname,DataType)
inportblk = [blk '/' name];
constantblk = [blk '/' name ' constant']; 
delete_line(blk,[name '/1'],toport);
position = get_param(inportblk,'position');
delete_block(inportblk);
add_block('built-in/Constant',constantblk);
add_line(blk,[name ' constant/1'],toport);
set_param(constantblk,'position',position,'Value',varname,'OutDataTypeStr',DataType);




