function deletePortCallback(dialog,blockHandle)
%

%   Copyright 2018-2020 The MathWorks, Inc.
   
    %Get the selected port number cached in the dialog source property
    selectedPortNumber = dialog.getDialogSource.UserData1.SelectedRow;

    %If no row in the spreadsheet is selected, we will delete the first port 
    if isempty(selectedPortNumber)
        selectedPortNumber = 1;
    end
    
    ss = dialog.getWidgetInterface('SimscapeSpreadsheet');
    if ~isempty(ss)        
        if ~isempty(selectedPortNumber) 
            
            %Get the port handles for the brancher block
            portHandles = get_param(blockHandle,'PortHandles');
            
            %Get the handle for the selected port 
            selectedPortHandle = portHandles.LConn(selectedPortNumber);
            
            %Checking the consistency in states between the dialog and the block
            blockState = get_param(blockHandle,'hierStrings');        
            dialogState = dialog.getDialogSource.UserData1.PortStrings;

            blockPortConnectivity = get_param(blockHandle,'PortConnectivity');
            dialogPortConnectivity = dialog.getDialogSource.UserData1.PortConnectivity;

            dialog.getDialogSource.UserData1.SelectedRow = [];
    
            %If the dialog and block are consistent, then proceed with the
            %delete operation, else do nothing but refresh. 

            if (isequal(dialogState,blockState) && isequal(blockPortConnectivity,dialogPortConnectivity)...
               && ~isSimscapeBusDialogStale(blockHandle, dialog))
           
                %Set a flag which ensures getChildren just reuses children data
                %from UserData.m_children
                dialog.getSource.UserData.shouldRecreateSpreadsheet = false;
                
                children = dialog.getSource.UserData.m_Children;
                numChildren = numel(children); 
                
                %For all the spreadsheet rows below the selected row, the
                %port number must be decremented in the UserData cache. 
                for i = (selectedPortNumber+1) : numChildren
                    children(i).portNumber = children(i).portNumber -1; 
                end
                dialog.getSource.UserData.m_Children = children; 
                % Remove entry from UserData 
                dialog.getSource.UserData.m_Children(selectedPortNumber) = [];
                
                %Delete the port corresponding to the selected port handle
                SLM3I.SLDomain.deletePortOnBlock(selectedPortHandle);
            end
        end
    end
 end
