Attribute VB_Name = "MenuPrc"
Option Explicit

Public Enum MENUTOOLTAG
    ' this enum is used for menu tool in the tools collection
    ' it is not used for any tools in a band collection - the tag is used for other things in this instance
    MENUTOOL_SEPARATOR = 1  ' used to signify that there is a separator before this item (even if this is hidden)
    MENUTOOL_DISABLE = 2    ' takes precedence
    MENUTOOL_ENABLE = 4
    MENUTOOL_ENABLEMASK = 6
    MENUTOOL_HIDE = 8       ' takes precedence
    MENUTOOL_SHOW = 16
    MENUTOOL_VISIBLEMASK = 24
    MENUTOOL_UPDATE = 32    ' used to ensure permissions are refreshed
    MENUTOOL_CHANGEDMASK = 3134 ' 2 + 4 + 8 + 16 + 32 + 1024 + 2048
    MENUTOOL_INSERTEDINMENU = 64    ' used to note that the tool been inserted in a menu (this is ALSO set by toolbar builder application - to say it has its position already)
    MENUTOOL_SEPARATORNEXT = 128  ' used on append menu item to indicate the next item has a separator
    MENUTOOL_VISIBLEATSTARTUP = 256  ' used to note that this tool is normally visible at startup (set by toolbar builder application)
    MENUTOOL_ISACCESSCONTROLLED = 512   ' used ONLY in the designer to state that this item is under access control
    MENUTOOL_CHECKMASK = 3072
    MENUTOOL_CHECK = 1024
    MENUTOOL_UNCHECK = 2048
End Enum

Public Enum GENERICTYPE
    GENERICTYPE_NONE = 0
    GENERICTYPE_GENERIC = 1
    GENERICTYPE_MATRIX = 2
    GENERICTYPE_TAU = 3
End Enum

' leave lower WORD clear for MF_ constants, see MSDN / Object Browser
Private Const SA_MF_DRAWINGTOOL As Long = 1 * 2 ^ 16
Private Const SA_MF_DONTSYNCH As Long = 2 * 2 ^ 16

Public bUpdateSymbolStyleBar As Boolean
Public enuUpdateGenericActive As GENERICTYPE
Public bMenusChanged As Boolean
Public bRedrawNextTimer As Boolean
Public bSAIsBusy As Boolean
Public g_blnSAIsBusy_ProcessingDiagramLogic As Boolean  ' True if sadesign is managing the opening of a diagram - need to switch off the MDI Active checks
Public g_blnSAIsBusy_DoNOTProcessVBAEvents As Boolean  ' When True no VBA Events will be processed - used during diagram shutdown for a critical region of code
Public g_blnSAIsBusy_ProcessingGenericOpen As Boolean  ' True if a generic form is opening - stops it being closed before it is open
Public g_blnSAIsBusy_ProcessingObjModelDgmOpen As Boolean ' True when the object model is opening/creating a diagram
Public g_blnSAIsBusy_ProcessingObjectHistory As Boolean ' True when processing compares for object history

Public dicStereoDrawTools As Dictionary ' tool id (long) of popup, key is dgmtype & usermode & name of first child item
' ^ the key info is needed in KillDrawMenus to identify the bands to be removed

Public bInhibitMenuTimer As Boolean
Private LastToolAddedSubID As String
Private LastToolAddedSubBand As String
Private LastToolAddedToolID As Long
Private LastDrawPopupAddedToolID As Long
Private sLastDrawPopupParentBand As String

Private DrawToolbarSubBandID  As Long

Private bDrawMenuAddingStereoTypes As Boolean
Private bWarnedOnBreakingStereotypeBandLimit As Boolean

Public dicDrawPopupsByTypeModeName As New Dictionary
Public dicDrawMenusByTypeModeName As New Dictionary ' DrawMenu object, or key for toolbar
Private objLastDrawPopupTool As SAToolbarTool
Public g_strLastDrawRootPopupToolNameHoveredOver As String
Public g_strLastDrawRootPopupToolName As String
Public g_strLastDrawToolName As String
Private g_lngDgmTypeBeingOpened As Long ' set by DrawMenu_RestoreForType, used in DrawMenu_SetupDrawMenuTool

#If TOOLDEBUGGING Then
Private strLogMessageToolsPrefix As String
#End If

Private Declare Sub ReleaseDiagramTypeXml Lib "sadesign" Alias "_ReleaseDiagramTypeXML@4" (ByVal lpstrXml As Long)
Public g_bCacheDrawMenus As Boolean

Public Function GetFreeMacroId() As Long
End Function

Public Sub ShowMenuCounts()
    ' dummy - delete when removed from FSAMain1.frm
End Sub

Public Sub Menu_Timer()
    If bInhibitMenuTimer Or g_blnSAIsBusy_ProcessingDiagramLogic Then Exit Sub ' No menu timer, or diagram logic is being established - then abort
    If bMenusChanged Then
        bRedrawNextTimer = True
        bMenusChanged = False
        bSAIsBusy = False
    ElseIf bSAIsBusy Then
        ' - allow SA to say it is busy even if menus have not changed
        bSAIsBusy = False           ' just delay
    ElseIf bRedrawNextTimer Then
        RedrawMenu
    End If
End Sub

Public Sub UpdateAllToolPermissions()
    Dim objTool As SAToolbarTool
    Dim lngIndex As Long
    Dim menuFlags As Long
    Dim lngID As Long
    
    For lngIndex = 0 To fMainForm.ATB.Tools.Count - 1
        ' Process all of the tools
        Set objTool = fMainForm.ATB.Tools(lngIndex)
        
        If objTool.ROState <> SATOOLBAR_ROSTATE_NORMAL Then
            ' This tool has special behaviour when the encyclopedia is open Read Only
            ' This ROState system works by allowing SA in general to believe all the menus are being displayed as usual
            ' sa2001 is hiding, showing, enabling and disabling then, and sadesign is happily removing, adding enabling and disabling them.
            ' We know that some menu items should not be available if the ency is read only, so these are marked in the satbf.tbf
            ' ROState = "1"  - means disable, and = "2" means hide (currently unused)
            ' The permissions logic already hides and disables menu items at the last moment in sa2001, this has been extended
            ' to reduce permissions on these other menu items if the ency is read only.
            ' The logic in here has been changed slightly because, subsequently when a workspace is opened which is read/write
            ' we must re-show and enable items which should be available to the user. This is something the permissions logic
            ' did not need to cope with, as the ency was re-opened and all the menus were reset.
            ' To do this we utilise the old internal menu system in sadesign, which has kept track of the enabled state of the item
            ' despite it being overridden in sa2001. So we call down to sadesign and determine the correct state and attempt to
            ' reapply it. We say attempt because the catalog manager permissions may override it anyway.
            ' As a result this ROState logic is only useful for menu items which also exist in the sadesign sa.mnu system.
            ' Using ROState on other menu items may result in disabled tools, when switching back to a read write environment
            lngID = objTool.toolID
            'menuFlags = sadesign.SAObjGetInternalMenuState(SAShMenu, lngID, MF_BYCOMMAND)

            If menuFlags <> -1 Then
                ' Found the menu item
                If (menuFlags And MF_GRAYED) <> MF_GRAYED Then  ' Test for grayed, not MF_ENABLED (enabled is not a real flag)
                    ' Internally sadesign believes this menu item should be enabled, so we attempt to re-enable it
                    ' This happens when a user flips from a RO workspace to a RW workspace
                    objTool.UpdateFlags = objTool.UpdateFlags Or MENUTOOL_ENABLE
                    objTool.UpdateFlags = objTool.UpdateFlags Or MENUTOOL_SHOW  ' We show it as well, since it exists internally, so should be shown
                End If
' This is not currently required, and may never be required. The idea that a menu we are looking for is not
' in the sadesign menu system, may have various implications. It could be a macro, a special SA2001 menu etc
' So hiding may not be the answer. I am leaving this code here in case it is required.
'            Else
'                ' Menu not found - so hide
'                objTool.UpdateFlags = objTool.UpdateFlags Or MENUTOOL_HIDE
            End If
        End If
        
        objTool.UpdateFlags = objTool.UpdateFlags Or MENUTOOL_UPDATE    ' Force a permissions update at the very least
    Next
    bMenusChanged = True
End Sub

Public Sub RedrawMenu()
    Dim sPermID As String
    Dim lFlags As Long
    Dim bRecalc As Boolean
    Dim blnMatrixVisible As Boolean
    Dim blnTAUVisible As Boolean
    Dim strProjectName As String
    Dim strModuleName As String
    Dim strProcName As String
    Dim strCaption As String
    Dim strPermID As String
    Dim objToolBox As SAToolbarBand
    Dim lToolID As Long
    Dim sToolName As String
    
    bInhibitMenuTimer = True
    If bMenusChanged Or bRedrawNextTimer Then
        If Not CmdLineNoRedraw Then fMainForm.ATB.RecalcLayout '***** THIS KILLS US IF WE BREAKPOINT in VBA Event ReportMenuUpdate AND CLOSE DIAGRAM - now blocked by g_lngSAIsBusy_ProcessingDiagramLogic higher up
        
#If TOOLDEBUGGING Then
        LogMessageTools "Redraw Menu Timer about to start" 'DEV_STRING
#End If
        
        If bUpdateSymbolStyleBar Then
            ' Update the stylebar with the latest symbol selection
            bUpdateSymbolStyleBar = False   ' Don't update again next time
            
            Call UpdateSymbolStyleBar(fMainForm.ATB)
            bRecalc = True
        End If

        ' Matrix Editor Menu Updater
        If Not g_objCurrentMatrix Is Nothing Then
            blnMatrixVisible = True ' There is a matrix so show the menu
        End If
        If Not g_objCurrentTAU Is Nothing Then
            blnTAUVisible = True ' There is a TAU window so show the menu
        End If
        EnableMatrixTools fMainForm.ATB, blnMatrixVisible
        EnableTAUTools fMainForm.ATB, blnTAUVisible
        If enuUpdateGenericActive <> GENERICTYPE_NONE Then
            ' Update the menus/toolbars now that a generic window is active
            If enuUpdateGenericActive = GENERICTYPE_MATRIX Then
                ' Enable the matrix bar and setup check items
                Call SetupMatrixMenu(fMainForm.ATB)
                bRecalc = True
            End If
            enuUpdateGenericActive = GENERICTYPE_NONE   ' Don't update again next time
        End If
        ' End of Matrix Menu Updater
        
        Dim atTool As SAToolbarTool
        Dim lngToolPos As Long
                
        For lngToolPos = fMainForm.ATB.Tools.Count - 1 To 0 Step -1
            If lngToolPos >= fMainForm.ATB.Tools.Count Then
                lngToolPos = fMainForm.ATB.Tools.Count - 1
            End If
            Set atTool = fMainForm.ATB.Tools(lngToolPos)
            
            If (atTool.UpdateFlags And MENUTOOL_CHANGEDMASK) <> 0 Then
                lToolID = atTool.toolID
                If (atTool.UpdateFlags And MENUTOOL_ENABLEMASK) = MENUTOOL_DISABLE Then
                    atTool.UpdateFlags = atTool.UpdateFlags And (Not MENUTOOL_UPDATE)  ' Ignore permissions it is being hidden
                    atTool.Enabled = False
                ElseIf (atTool.UpdateFlags And MENUTOOL_ENABLEMASK) = MENUTOOL_ENABLE Then
#If TOOLDEBUGGING Then
                    LogMessageTools "RedrawMenu - Enabling tool -" & atTool.name 'DEV_STRING
#End If
                    atTool.UpdateFlags = atTool.UpdateFlags Or MENUTOOL_UPDATE  ' Ensure permissions are adhered to
                    atTool.Enabled = True
                End If
                If (atTool.UpdateFlags And MENUTOOL_CHECKMASK) = MENUTOOL_UNCHECK Then
                    atTool.UpdateFlags = atTool.UpdateFlags And (Not MENUTOOL_UPDATE)  ' Ignore permissions it is being hidden
                    atTool.Checked = False
                ElseIf (atTool.UpdateFlags And MENUTOOL_CHECKMASK) = MENUTOOL_CHECK Then
#If TOOLDEBUGGING Then
                    LogMessageTools "RedrawMenu - Checking tool -" & atTool.name 'DEV_STRING
#End If
                    atTool.UpdateFlags = atTool.UpdateFlags Or MENUTOOL_UPDATE  ' Ensure permissions are adhered to
                    atTool.Checked = True
                End If
                If (atTool.UpdateFlags And MENUTOOL_VISIBLEMASK) = MENUTOOL_HIDE Then
                    DoRemoveOrHideTool fMainForm.ATB, atTool.name
                    atTool.UpdateFlags = atTool.UpdateFlags And (Not MENUTOOL_UPDATE)  ' Ignore permissions it is being hidden
                    bRecalc = True
                ElseIf (atTool.UpdateFlags And MENUTOOL_VISIBLEMASK) = MENUTOOL_SHOW Then
#If TOOLDEBUGGING Then
                    LogMessageTools "RedrawMenu - Showing tool -" & atTool.name 'DEV_STRING
#End If
                    atTool.UpdateFlags = atTool.UpdateFlags Or MENUTOOL_UPDATE  ' Ensure permissions are adhered to
                    atTool.Visible = True
                    bRecalc = True
                End If
                
                If ((atTool.UpdateFlags And MENUTOOL_UPDATE) <> 0) Then
                    If IsMacroTool(atTool.toolID) Then
                    Else
                        ' This is an ordinary menu item
                        ' Handle Permission Info
                        strCaption = atTool.Caption
                        sToolName = atTool.name
                        GetPermissionState PER_MENU, atTool.toolID, lFlags, atTool

#If TOOLDEBUGGING Then
                        LogMessageTools "RedrawMenu - Pre Permission state is - Tool=" & atTool.Enabled & " Audit=" & SAValidAuditID & " lFlags=" & lFlags 'DEV_STRING
#End If
                        If 0 = (lFlags And PERFLAG_ENABLED) Then
                            ' The item is not permitted to be enabled so disable it
                            atTool.Enabled = False
                        End If
                        If 0 = (lFlags And PERFLAG_VISIBLE) Then
                            ' The item is not permitted to be seen, so hide it
                            atTool.Visible = False
#If TOOLDEBUGGING Then
                            LogMessageTools "Permission blocked visible for " & atTool.name 'DEV_STRING
#End If
                            bRecalc = True
                        End If
                    End If
                End If

                ' Clear the changed flag
                atTool.UpdateFlags = atTool.UpdateFlags And (Not MENUTOOL_CHANGEDMASK)
            End If
        Next
                
        'TODO TOOLBAR Find a better place for this as we only need to enable these tools once
        fMainForm.ATB.Tools("id_Window").Enabled = True 'DEV_STRING
        fMainForm.ATB.Tools("SAIDM_500").Enabled = True 'DEV_STRING
        fMainForm.ATB.Tools("SAIDM_501").Enabled = True 'DEV_STRING
        fMainForm.ATB.Tools("SAIDM_502").Enabled = True 'DEV_STRING
        fMainForm.ATB.Tools("SAIDM_503").Enabled = True 'DEV_STRING
        fMainForm.ATB.Tools("SAIDM_506").Enabled = True 'DEV_STRING
        fMainForm.ATB.Tools("SAIDM_504").Enabled = True 'DEV_STRING
        
        If gsEncyName <> SA_VB_EmptyString Then
            fMainForm.ATB.Tools("SAIDM_798").Enabled = True 'DEV_STRING
        End If
        
        'TODO TOOLBAR - this might go elsewhere?
        'Set objToolBox = fMainForm.ATB.Bands(sToolboxBand)
        'If objToolBox.Tools.Count <= 2 Then
            ' NB: One non SA tool is always in the draw toolbar ("Toolbar Options" ID=9400)
            ' Another non SA tool may be in the draw toolbar ("Close" ID=9401)
            'objToolBox.Visible = False
        'End If
        
        fMainForm.ATB.Update = True
    End If
    bRedrawNextTimer = False
    bMenusChanged = False
    bSAIsBusy = False
    bInhibitMenuTimer = False
End Sub

Public Function Do_Insert_Menu_Proc(ByVal hMenu As Long, _
                                 ByVal uPosition As Long, _
                                 ByVal uFlags As Long, _
                                 ByVal uIDNewItem As Long, _
                                 ByVal lpszNewItem As Long _
                                 ) As Long
    
    If CmdLineNoMenu Then Exit Function
    
    Dim blnNewTool As Boolean
    Dim bIsSubType As Boolean
    bIsSubType = False
    If (uFlags And MF_POPUP) = 0 Then
        If (uIDNewItem And &HFFFF0000) <> 0 Then bIsSubType = True
        uIDNewItem = uIDNewItem And 65535
    End If
    Dim objTool As SAToolbarTool
    Dim objBand As SAToolbarBand
    Dim sCaption As String
    Dim s As String
    Dim uIDUse As Long
    '''''If DisableCount = 0 Then
    '''''    LogMessage "Insert_Menu_Proc - menu redraw not disabled"
    '''''End If
    
    '
    ' second guess the main menu handle
    '
    If SAShMenu = 0 Then SAShMenu = hMenu
    
    Dim ParentMenu As String
    Dim ParentBand As String
    If hMenu = SAShMenu Then
        
        ParentMenu = SAXRes.GetLocalString(IDS_uloc_____mainmenu)
        
    Else
        ParentMenu = GethMenuID(SAShMenu, hMenu)
    End If
    If ParentMenu = SA_VB_EmptyString Then Exit Function  ' not for us.
    If ParentMenu = BAND_DRAWMENU Then
        If strDrawMenu = ParentMenu Then ' do as in Do_Append in case this is needed
            DrawMenu_SetupDrawMenuTool g_lngDgmTypeBeingOpened, GetUserMode()
        End If
        ParentBand = strDrawMenu ' ParentMenu & GetActiveDiagramType() & GetUserMode()
    Else
        ParentBand = ParentMenu
    End If
    
    Dim Id As String
    If (uFlags And MF_BYPOSITION) <> 0 Then
        ' +1 as we are called after the insertion into hMenu
        Id = SSFullGetMenuID(hMenu, uPosition + 1, uFlags)
    Else
        Id = SSFullGetMenuID(hMenu, uPosition, uFlags)
    End If
    If Id = SA_VB_EmptyString Then Exit Function
    
    If (lpszNewItem <> 0) Then
        sCaption = PointerToString(lpszNewItem)
    End If
    
    Dim NewID As String
    If (uFlags And MF_POPUP) <> 0 Then
        NewID = "id_" & CleanMenuID(sCaption) 'DEV_STRING
    Else
        NewID = SSGetMenuID(uIDNewItem)
        s = sCaption    ' Non-Popups have their caption changed IF required
    End If
    
    bMenusChanged = True    ' flag for updating
    
    Dim errFlag As Boolean
    errFlag = False
    On Error GoTo MenuError
    fMainForm.SSAtbUpdating = True

    If (uFlags And MF_POPUP) = MF_POPUP Then
      uIDUse = -1   ' Popup item - use generated ID
    Else
      uIDUse = uIDNewItem   ' Not Popup item - use the given ID
    End If
    blnNewTool = CheckAddTool(fMainForm.ATB, (uFlags And MF_POPUP) <> 0, uIDUse, NewID, s)  ' We don't supply a caption for popups yet!
    
    If (uFlags And MF_POPUP) <> 0 And (uFlags And SA_MF_DONTSYNCH) = 0 Then
        SynchronizeMenu fMainForm.ATB, NewID, uIDNewItem
    End If
    
    If blnNewTool Then
#If TOOLDEBUGGING Then
        Call LogMessageTools("MenuPrc-Do_Insert_Menu_Proc- Insert tool '" & NewID & "'") 'DEV_STRING
#End If
        ' This tool did not exist - give it the caption
        ' Use the caption provided
        Set objTool = fMainForm.ATB.Tools(NewID)
        objTool.Caption = sCaption
           
        With fMainForm.ATB
            If (uFlags And MF_BYPOSITION) <> 0 Then
                InsertInTools ParentBand, GetIndex(.Bands(ParentBand).Tools, Id), .Tools(NewID)
            Else
                InsertInMenu fMainForm.ATB, .Bands(ParentBand), Id, .Tools(NewID)
            End If
        End With
    End If
    
#If TOOLDEBUGGING Then
    Call LogMessageTools("MenuPrc-Do_Insert_Menu_Proc- Show tool '" & NewID & "'") 'DEV_STRING
#End If
    ShowMenuTool fMainForm.ATB, fMainForm.ATB.Tools(NewID), True
    
    If (uFlags And (MF_DISABLED Or MF_GRAYED)) <> 0 Then
        EnableMenuTool fMainForm.ATB.Tools(NewID), False
    End If
    
    fMainForm.SSAtbUpdating = False
    'If ErrFlag = False Then logmessage "Insert_Menu_Proc inserted:" & s & " " & NewID & " " & Format(uIDNewItem)
    On Error GoTo 0
    
    Exit Function
    
MenuError:
    errFlag = True
    
    LogMessage "Insert_Menu_Proc ERROR " & sCaption & Space(1) & NewID & Space(1) & Format(uIDNewItem) & Space(1) & Id & _
        " flags:" & Hex(uFlags) & " hMenu,pos:" & Hex(hMenu) & SA_VB_Comma & Format(uPosition) _
        & " GethMenuID:" & GethMenuID(SAShMenu, hMenu) 'DEV_STRING
    
    Resume Next

End Function

' uFlags - lower word is for MF_ constants
Public Function Do_Append_Menu_Proc(ByVal hMenu As Long, _
                                 ByVal uFlags As Long, _
                                 ByVal uIDNewItem As Long, _
                                 ByVal lpszNewItem As Long _
                                 ) As Long
'
If CmdLineNoMenu Then Exit Function
    
    Dim bIsSubType As Boolean
    Dim blnNewTool As Boolean
    Dim ParentToolName As String
    Dim lngInsertAt As Long
    Dim sCaption As String
    Dim objTool As SAToolbarTool
    Dim objBand As SAToolbarBand
    Dim s As String
    Dim b As Boolean
    Dim bSpecialPopup As Boolean
    Dim lToolID As Long
    
    
    lngInsertAt = -1
    
    bIsSubType = False
    If (uFlags And MF_POPUP) = 0 Then
        If (uIDNewItem And &HFFFF0000) <> 0 Then bIsSubType = True
        uIDNewItem = uIDNewItem And 65535
    End If
    
    Dim uIDUse As Long
    Dim bSeparator As Boolean
    '''''If DisableCount = 0 Then
    '''''    LogMessage "Append_Menu_Proc - menu redraw not disabled"
    '''''End If
    
''' done below    If Not bCheckMenuHandle(SAShMenu, hMenu) Then Exit Function  ' not for us.
    Dim ParentMenu As String
    Dim ParentBand As String
    If hMenu = SAShMenu Then
        ParentMenu = strMainMenu
    Else
        ParentMenu = GethMenuID(SAShMenu, hMenu)
    End If
    If ParentMenu = SA_VB_EmptyString Then Exit Function   ' can't cope with appending to a menu we do not have yet
    If ParentMenu = BAND_DRAWMENU Then
        If strDrawMenu = ParentMenu Then
            DrawMenu_SetupDrawMenuTool g_lngDgmTypeBeingOpened, GetUserMode()
        End If
        ParentBand = strDrawMenu ' ParentMenu & GetActiveDiagramType() & GetUserMode()
    Else
        ParentBand = ParentMenu
    End If
    
    If (lpszNewItem <> 0) Then
        sCaption = PointerToString(lpszNewItem)
    End If
       
#If TOOLDEBUGGING Then
    Call LogMessageTools("MenuPrc-Do_Append_Menu_Proc: uIDNewItem=" & Format(uIDNewItem) & " Caption='" & sCaption & "'") 'DEV_STRING
    strLogMessageToolsPrefix = Space$(Len(strLogMessageToolsPrefix) + 1)
#End If
    Dim NewID As String
    If (uFlags And MF_POPUP) <> 0 Then
        NewID = "id_" & CleanMenuID(sCaption) 'DEV_STRING
        If (uFlags And SA_MF_DRAWINGTOOL) <> 0 Then
            If NewID = BAND_DRAWMENU Then
                NewID = strDrawMenu
            ElseIf NewID <> BAND_DRAWLINEMENU And NewID <> BAND_DRAWNODEMENU Then
                NewID = "id_" & GetActiveDiagramType() & GetUserMode() & CleanMenuID(sCaption) 'DEV_STRING
            End If
            If Not dicDrawPopupsByTypeModeName.Exists(NewID) Then
                dicDrawPopupsByTypeModeName.Add NewID, NewID
            End If
        End If
    Else
        s = sCaption    ' Non-Popups have their caption changed IF required
        
        ' we cannot cope with appending separators - and any way
        ' append is used to add a separator to unattached hMenus
        If uIDNewItem = 0 And (uFlags And MF_SEPARATOR) <> 0 Then
            With fMainForm.ATB.Bands(ParentBand).Tools
                If .Count > 0 Then
                    ' remember that a separator is needed on the next one
                    On Error Resume Next ' Tried to add a menu item to Draw menu and another menu and the result was that on the 2nd open of a diagram we got here then this statement failed..
                    .Item(.Count - 1).UpdateFlags = .Item(.Count - 1).UpdateFlags Or MENUTOOL_SEPARATORNEXT
                    On Error GoTo 0
                End If
            End With
            Exit Function
        End If
        
        NewID = SSGetMenuID(uIDNewItem)
    End If
    
    If CmdLineNoMenu Then Exit Function
    
    bMenusChanged = True    ' flag for updating
    
    On Error GoTo MenuError
    fMainForm.SSAtbUpdating = True

    If (uFlags And MF_POPUP) = MF_POPUP Then
      uIDUse = -1   ' Popup item - use generated ID
    Else
      uIDUse = uIDNewItem   ' Not Popup item - use the given ID
    End If
    bSpecialPopup = (uFlags And MF_POPUP) <> 0 And (uFlags And SA_MF_DRAWINGTOOL) <> 0
    If bSpecialPopup Then
        bSpecialPopup = True ' for breakpointing on in VC
    End If
    blnNewTool = CheckAddTool(fMainForm.ATB, (uFlags And MF_POPUP) <> 0, uIDUse, NewID, s, , , lToolID, objTool, bSpecialPopup) ' We don't supply a caption for popups yet!
    
    If (uFlags And MF_POPUP) <> 0 Then
        SynchronizeMenu fMainForm.ATB, NewID, uIDNewItem
    End If
    
    If blnNewTool Or ((ParentMenu = BAND_DRAWLINEMENU Or ParentMenu = BAND_DRAWNODEMENU) And IsDrawingTool(uIDNewItem)) Or (uFlags And SA_MF_DRAWINGTOOL) <> 0 Then
        ' Tool didn't exist - so add using non-decoupled code
        ' DECOUPLE TOOLBAR - this could be removed if no tools were ever added by code
        
        ' This tool did not exist - give it the caption
        ' Use the caption provided
        objTool.Caption = sCaption
        
        With fMainForm.ATB.Bands(ParentBand).Tools
            objTool.IsDrawMenuPopup = bSpecialPopup
            If bSpecialPopup Then
                objTool.Style = SATB_ST_IconText
                'objTool.ControlType = SATB_TT_BUTTONDROPDOWN ' no let access; set up in SAToolbarBands.Add
                objTool.ToolTipText = objTool.Caption
            End If
            If ParentMenu = BAND_DRAWMENU Or ParentMenu = BAND_DRAWLINEMENU Or ParentMenu = BAND_DRAWNODEMENU Or (uFlags And SA_MF_DRAWINGTOOL) <> 0 Then 'DEV_STRING
            
                If .Count > 0 Then 'i.e. this is not the first item
                    b = False
                    On Error Resume Next ' Tried to add a menu item to Draw menu and another menu and the result was that on the 2nd open of a diagram we got here then this statement failed..
                    b = 0 <> (.Item(.Count - 1).UpdateFlags And MENUTOOL_SEPARATORNEXT)
                    On Error GoTo MenuError
                    If b Then
                        bSeparator = True
                        On Error Resume Next ' Tried to add a menu item to Draw menu and another menu and the result was that on the 2nd open of a diagram we got here then this statement failed..
                        .Item(.Count - 1).UpdateFlags = .Item(.Count - 1).UpdateFlags And (Not MENUTOOL_SEPARATORNEXT)  ' Clear separator next flag
                        On Error GoTo MenuError
                    Else
                        bSeparator = False
                    End If
                End If
                
                If bIsSubType Then
                    If Not bDrawMenuAddingStereoTypes Then ' this is the first one
                        ParentToolName = LastToolAddedSubID
                    End If
                End If
                
                EnsureToolboxExists
                ' do this before adding the tool below as it sets up stuff for the stereo logic
                If ParentMenu = BAND_DRAWMENU Then
                    TryAddDrawMenuItemToDrawSubMenu sToolboxBand, uIDNewItem, False, bSeparator, bIsSubType
                    If bSpecialPopup Then ' The above only handles tools
                        lngInsertAt = FindLastDrawingToolPos(fMainForm.ATB.Bands(sToolboxBand).Tools)
                        InsertInTools sToolboxBand, lngInsertAt, objTool
                        LastDrawPopupAddedToolID = objTool.toolID
                        sLastDrawPopupParentBand = ParentBand
                    End If
                ElseIf (uFlags And SA_MF_DRAWINGTOOL) <> 0 Then
                    TryAddDrawMenuItemToDrawSubMenu ParentMenu, uIDNewItem, False, bSeparator, bIsSubType
                End If
                
                If ParentMenu = BAND_DRAWMENU Or ParentMenu = BAND_DRAWLINEMENU Then
                    lngInsertAt = fMainForm.ATB.Bands(ParentBand).Tools.Count
                    ' This ensures sequence remains as programmed in methdlgy.cmd and associated code
                Else
                    lngInsertAt = FindLastDrawingToolPos(fMainForm.ATB.Bands(ParentBand).Tools)
                End If
            End If
            If bSpecialPopup Then
                LastDrawPopupAddedToolID = objTool.toolID
                Set objLastDrawPopupTool = objTool
                sLastDrawPopupParentBand = ParentBand
            End If
            If ParentMenu = BAND_DRAWMENU _
            Or bSpecialPopup Then
                ' This block adds..
                ' root Draw menu items
                ' popup items because they always have a new id
                If bIsSubType Then
                    Dim aTBTool As SAToolbarTool
                    If Not bDrawMenuAddingStereoTypes Then ' this is the first one
                        Dim iId As Long, sID As String, sNewID As String, sNewID1 As String
                        
                        bDrawMenuAddingStereoTypes = True
                        
                        ' remove the last one
    '                    sID = .Item(lngInsertAt).Name
    '                    iId = .Item(lngInsertAt).toolID
    '                    .Remove  sID
                        .Remove ParentToolName
                        lngInsertAt = lngInsertAt - 1
                        ' Create and insert a new popup
    '                    sNewID1 = "TB_" & Format(iId)
                        sNewID1 = LastToolAddedSubBand
                                            
                        If .Count <= lngInsertAt Then
                            lngInsertAt = -1    ' Append
                        End If
                        InsertInTools ParentBand, lngInsertAt, fMainForm.ATB.Tools(sNewID1)
                    End If
                Else
                    InsertInTools ParentBand, lngInsertAt, objTool
                End If
            ElseIf (uFlags And SA_MF_DRAWINGTOOL) = 0 Then ' not a Drawing tool; handled above
                InsertInTools ParentBand, lngInsertAt, objTool
            End If
            If lngInsertAt > 1 Then 'i.e. this is not the first item
                If 0 <> (.Item(lngInsertAt - 2).UpdateFlags And MENUTOOL_SEPARATORNEXT) Then
                    .Item(lngInsertAt - 2).UpdateFlags = .Item(lngInsertAt - 2).UpdateFlags And Not MENUTOOL_SEPARATORNEXT
                    Call SetToolSeparator(.Item(lngInsertAt - 1), True)
'' This is done at band open by CalculateSeparators                    .Item(lngInsertAt - 1).BeginGroup = True
                End If
            End If
        End With
    ElseIf ParentMenu = BAND_DRAWMENU Then
        ' allow existing items to be moved
        fMainForm.ATB.Bands(ParentBand).Tools.Remove objTool.name
        fMainForm.ATB.Bands(ParentBand).Tools.Insert fMainForm.ATB.Bands(ParentMenu).Tools.Count, objTool
    End If
    If bIsSubType Then
' TODO TOOLBAR - Uncomment and fix this so it remembers the last stereotype tool chosen (when the tool was not selected) when flipping diagrams
' TODO TOOLBAR - it makes tools disappear when flipping diagrams at present?? - CR20660
'        On Error Resume Next
'        Dim lActiveID As Long
'        lActiveID = fMainForm.ActiveForm.collTBSubs(LastToolAddedSubBand)
'        If lActiveID = uIDNewItem Then
'            Set aTBTool = fMainForm.ATB.Bands(LastToolAddedSubBand).Tools(NewID)
'            With fMainForm.ATB.Bands("id_" + CleanMenuID(SAXRes.GetLocalString(IDSMenuDraw))).Tools(LastToolAddedSubBand)
'                .Caption = aTBTool.Caption
'                .ToolTipText = aTBTool.ToolTipText
'                .UpdateFlags = aTBTool.UpdateFlags
'            End With
'        End If
'        On Error GoTo 0
    Else
        bDrawMenuAddingStereoTypes = False
    End If
    
#If TOOLDEBUGGING Then
    Call LogMessageTools("MenuPrc-Do_Append_Menu_Proc- Show tool '" & NewID & "'") 'DEV_STRING
#End If
    ShowMenuTool fMainForm.ATB, objTool, True
    
    If (uFlags And (MF_DISABLED Or MF_GRAYED)) <> 0 Then
        EnableMenuTool objTool, False
    End If
    
    fMainForm.SSAtbUpdating = False
    On Error GoTo 0
    
#If TOOLDEBUGGING Then
    strLogMessageToolsPrefix = Space$(Len(strLogMessageToolsPrefix) - 1)
    Call LogMessageTools("MenuPrc-Do_Append_Menu_Proc: End") ' DEVSTRING
#End If
    Exit Function
    
MenuError:
    
    LogMessage "Append_Menu_Proc ERROR " & sCaption & Space(1) & NewID & Space(1) & Format(uIDNewItem) & Format(uIDUse) & _
        " flags:" & Hex(uFlags) & " hMenu:" & Hex(hMenu) _
        & " GethMenuID:" & GethMenuID(SAShMenu, hMenu) 'DEV_STRING
    
    Resume Next
    
End Function

Public Function Do_Modify_Menu_Proc(ByVal hMenu As Long, _
                                 ByVal uPosition As Long, _
                                 ByVal uFlags As Long, _
                                 ByVal uIDNewItem As Long, _
                                 ByVal lpszNewItem As Long _
                                 ) As Long
    Dim bIsSubType As Boolean
    Dim objTool As SAToolbarTool
    Dim p   As Long
    Dim str As String
    Dim Id As String
    Dim errFlag As Boolean
    Dim iAttempting As Integer
    Dim bToolNotFound As Boolean
    
    
    iAttempting = 1
    Do_Modify_Menu_Proc = uFlags
    
    If CmdLineNoMenu Then Exit Function
    
    bIsSubType = False
    If (uFlags And MF_POPUP) = 0 Then
        If (uIDNewItem And &HFFFF0000) <> 0 Then bIsSubType = True
        uIDNewItem = uIDNewItem And 65535
    End If
    
    If Not bCheckMenuHandle(SAShMenu, hMenu) Then Exit Function  ' not for us.
        
    Dim s As String
    If (lpszNewItem <> 0) Then
        s = PointerToString(lpszNewItem)
    End If
    
    Dim NewID As String
    If (uFlags And MF_POPUP) <> 0 Then
        NewID = "id_" & CleanMenuID(s) 'DEV_STRING
    Else
        NewID = SSGetMenuID(uIDNewItem)
    End If
    If NewID = TOOL_DRAWMENU Then
        If Not strDrawMenu = TOOL_DRAWMENU Then
            NewID = strDrawMenu
        End If
    End If
    
    bMenusChanged = True    ' flag for updating
    
    errFlag = False
    On Error GoTo MenuError
    fMainForm.SSAtbUpdating = True
    With fMainForm.ATB
' USED TO ALLOW TOOL RENAMES - NOTE THIS WILL NOT BE INDEXED CORRECTLY - A QA REPORT IS DISPLAYED IF THIS HAPPENS
' .Tools(Id).Name = NewID
'
        If CmdLineQAReporting Then
                Id = SSFullGetMenuID(hMenu, uPosition, uFlags)
            If Id = SA_VB_EmptyString Then Exit Function
            
                If Id <> NewID Then
                SAMessageBox "A tool with ID=" & Id & " is having its ID change to " & NewID & vbCrLf & "This should not be allowed!"   'DEV_STRING
            End If
        End If

        iAttempting = 2
        Set objTool = .Tools(NewID)
        bToolNotFound = objTool Is Nothing
        
        iAttempting = 3
        p = InStr(s, Chr(9))
        If p > 0 Then
          str = Mid$(s, 1, p - 1)
        Else
          str = s
        End If
        
        If (uFlags And MF_POPUP) <> 0 Then
            If objTool.Caption = "" And objTool.Caption <> str Then
                objTool.Caption = str   ' We do NOT allow popup menu items to rename their caption once set
                ' we need to search all bands to see where this is and to change it there as well
                UpdateToolInBands fMainForm.ATB, NewID, str
            End If

            Set objTool.SubBand = .Bands(NewID)
            ' populate the popup????
            SynchronizeMenu fMainForm.ATB, NewID, uIDNewItem
        Else
            If objTool.Caption <> str Then
                objTool.Caption = str
                ' we need to search all bands to see where this is and to change it there as well
                UpdateToolInBands fMainForm.ATB, NewID, str
            End If

        '    .Tools(NewID).Type = ssTypeButton
#If TOOLDEBUGGING Then
            Call LogMessageTools("MenuPrc-Do_Modify_Menu_Proc- Modifying tool '" & NewID & SA_VB_SingleQuote) 'DEV_STRING
#End If
        
            If (uFlags And (MF_DISABLED Or MF_GRAYED)) <> 0 Then
                EnableMenuTool objTool, False ' flag for disable
            Else
                If Not EnableMenuTool(objTool, True) Then
                    ' flag for enable - failed
                    Do_Modify_Menu_Proc = uFlags Or MF_GRAYED   ' Notify the caller that it is greyed not enabled
                End If
            End If

        End If
    End With
    fMainForm.SSAtbUpdating = False
    'If ErrFlag = False Then logmessage "Modify_Menu_Proc Changed:" & s & " " & NewID & " " & Format(uIDNewItem)
    On Error GoTo 0
    
    Exit Function
    
MenuError:
    'On Error GoTo 0 ' Don't do this; when an error occurs in a called routine the Resume Next below can just trigger the error handler in saidlg and you get an 'unknown error' dialog
    ' and since these errors started being observed this code was put in place. All that will happen on such an error is that we will get two error logs.
    ' See WI32691, apparent cause was the prep of the extra Draw menus when the diagram was opened read-only.
    errFlag = True
    
    LogMessage "Modify_Menu_Proc ERROR " & NewID & Space(1) & s & Space(1) & SSGetMenuID(uIDNewItem) & _
        " flags:" & Hex(uFlags) & " hMenu,pos:" & Hex(hMenu) & SA_VB_Comma & Format(uPosition) _
        & " GethMenuID:" & GethMenuID(SAShMenu, hMenu) & ", iAttempting=" & iAttempting & ", bToolNotFound=" & bToolNotFound 'DEV_STRING
    
    Resume Next
 
End Function

Public Function Do_Remove_Menu_Proc(ByVal hMenu As Long, _
                                 ByVal uPosition As Long, _
                                 ByVal uFlags As Long _
                                 ) As Long
    If CmdLineNoMenu Then Exit Function
    
    '''''If DisableCount = 0 Then
    '''''    LogMessage "Remove_Menu_Proc - menu redraw not disabled"
    '''''End If
    
''' done below    If Not bCheckMenuHandle(SAShMenu, hMenu) Then Exit Function  ' not for us.
    Dim ParentMenu As String
    Dim aTool As SAToolbarTool
    Dim blnDisabled As Boolean
    
    If hMenu = SAShMenu Then
        
        ParentMenu = SAXRes.GetLocalString(IDS_uloc_____mainmenu)
        
    Else
        ParentMenu = GethMenuID(SAShMenu, hMenu)
    End If
    If ParentMenu = SA_VB_EmptyString Then Exit Function   ' not for us
    
    Dim Id As String
    Id = SSFullGetMenuID(hMenu, uPosition, uFlags)
    If Id = SA_VB_EmptyString Then Exit Function
    If Id = TOOL_DRAWMENU Then
        Id = strDrawMenu
    End If
    
    bMenusChanged = True    ' flag for updating
    
    On Error GoTo MenuError
    fMainForm.SSAtbUpdating = True
    
    With fMainForm.ATB
#If TOOLDEBUGGING Then
        Call LogMessageTools("MenuPrc-Do_Remove_Menu_Proc- Hiding tool '" & Id & "'") 'DEV_STRING
#End If
        
        If ParentMenu = SAXRes.GetLocalString(IDS_uloc_____mainmenu) Then
            ' Special case to prevent top level menus vanishing - they grey out instead!!
            If ToolInATBCollection(fMainForm.ATB.Bands(SAXRes.GetLocalString(IDS_uloc_____mainmenu)).Tools, Id) Then
#If TOOLDEBUGGING Then
                Call LogMessageTools("MenuPrc-Do_Remove_Menu_Proc- Disabling tool '" & Id & "'") 'DEV_STRING
#End If
                EnableMenuTool fMainForm.ATB.Tools(Id), False   ' Disable menu - do not hide it
                blnDisabled = True
            End If
        End If
            
        If Not blnDisabled Then
            ' Item was not a top level menu - so hide it
#If TOOLDEBUGGING Then
            Call LogMessageTools("MenuPrc-Do_Remove_Menu_Proc- Hiding tool '" & Id & "'") 'DEV_STRING
#End If
            ShowMenuTool fMainForm.ATB, Id, False
        End If
        
        If ParentMenu = SAXRes.GetLocalString(IDS_uloc_____mainmenu) And Id = strDrawMenu Then 'DEV_STRING
            RemoveDrawToolBox
        ElseIf (uFlags And SA_MF_DONTSYNCH) = 0 Then
            SynchronizePopupMenuDecoupleRemove fMainForm.ATB, Id, hMenu, Id
        End If
        
        'If ParentMenu = strDrawMenu Then
        '    LogMessage "Removing " & id & " from the draw menu"
        'End If
    End With
    fMainForm.SSAtbUpdating = False
    On Error GoTo 0
    
    Exit Function
    
MenuError:
    On Error GoTo 0
    
    LogMessage "Remove_Menu_Proc ERROR hMenuID:" & ParentMenu & " ID:" & Id & _
        " flags:" & Hex(uFlags) & " hMenu,pos:" & Hex(hMenu) & "," & Format(uPosition) _
        & " GethMenuID:" & GethMenuID(SAShMenu, hMenu) 'DEV_STRING
    
    Resume Next
 
End Function

Public Function Do_Delete_Menu_Proc(ByVal hMenu As Long, _
                                 ByVal uPosition As Long, _
                                 ByVal uFlags As Long _
                                 ) As Long
'
    Dim lButtonID As Long
    Dim ParentMenu As String
    Dim Id As String
    Dim strStereoId As String
    Dim uID As Long
    Dim sBandName As String
    Dim sToolName As String
    Dim oBand As SAToolbarBand
    Dim blnDisabled As Boolean
    
    If CmdLineNoMenu Then Exit Function
    
    '''''If DisableCount = 0 Then
    '''''    LogMessage "Delete_Menu_Proc - menu redraw not disabled"
    '''''End If
    
    If hMenu = SAShMenu Then
        ParentMenu = strMainMenu
    Else
        ParentMenu = GethMenuID(SAShMenu, hMenu)
    End If
    If ParentMenu = SA_VB_EmptyString Then Exit Function ' not for us.
    
    Id = SSFullGetMenuID(hMenu, uPosition, uFlags)
    If Id = SA_VB_EmptyString Then Exit Function
    If Id = TOOL_DRAWMENU Then
        Id = strDrawMenu
    End If
    
    If Left(Id, 6) = "SAIDM_" Then 'DEV_STRING
        ' it is probably a drawing tool
        uID = val(Mid(Id, 7))
    End If
    On Error Resume Next
    strStereoId = GetActiveDiagramType() & GetUserMode() & Id
    lButtonID = dicStereoDrawTools(strStereoId)
    On Error GoTo 0
    
    bMenusChanged = True    ' flag for updating
    
    On Error GoTo MenuError
    fMainForm.SSAtbUpdating = True
    With fMainForm.ATB
        If lButtonID <> 0 Then      ' this is actually in a sub menu
            sToolName = "TB_" & Format(lButtonID) 'DEV_STRING
            sBandName = "TB_" & GetActiveDiagramType() & GetUserMode() & sToolName
            sToolName = sBandName
            
            Set oBand = .Bands(sBandName)
            ShowMenuTool fMainForm.ATB, Id, False
            dicStereoDrawTools.Remove strStereoId
            If oBand.Tools.Count = 0 Then
                ' we need to remove the 'parent' tool from the draw menu and the toolbox
                ShowMenuTool fMainForm.ATB, sToolName, False
'''                .Bands(ParentMenu).Tools.Remove sBandName
'''                .Bands(sToolboxBand).Tools.Remove sBandName
            End If
        Else
            
            If ParentMenu = strMainMenu Then
                ' Special case to prevent top level menus vanishing - they grey out instead!!
                If ToolInATBCollection(fMainForm.ATB.Bands(SAXRes.GetLocalString(IDS_uloc_____mainmenu)).Tools, Id) Then
#If TOOLDEBUGGING Then
                    Call LogMessageTools("MenuPrc-Do_Delete_Menu_Proc- Disabling tool '" & Id & "'") 'DEV_STRING
#End If
                    EnableMenuTool fMainForm.ATB.Tools(Id), False   ' Disable menu - do not hide it
                    blnDisabled = True
                End If
            End If
            
            If Not blnDisabled Then
                ' Item was not a top level menu - so hide it
#If TOOLDEBUGGING Then
                Call LogMessageTools("MenuPrc-Do_Delete_Menu_Proc- Hiding tool '" & Id & "'") 'DEV_STRING
#End If
                ShowMenuTool fMainForm.ATB, Id, False
            End If
            
            If ParentMenu = strMainMenu And Id = strDrawMenu Then 'DEV_STRING
                RemoveDrawToolBox
            ElseIf (uFlags And SA_MF_DONTSYNCH) = 0 Then
                SynchronizePopupMenuDecoupleRemove fMainForm.ATB, Id, hMenu, Id
            End If
        End If
    End With
    fMainForm.SSAtbUpdating = False
    On Error GoTo 0
    
    Exit Function
    
MenuError:
    On Error GoTo 0
    
    LogMessage "Delete_Menu_Proc ERROR hMenuID:" & ParentMenu & " ID:" & Id & _
        " flags:" & Hex(uFlags) & " hMenu,pos:" & Hex(hMenu) & "," & Format(uPosition) _
        & " GethMenuID:" & GethMenuID(SAShMenu, hMenu) 'DEV_STRING
    
    'If (uFlags And MF_BYPOSITION) <> 0 Then
    '    Dim mnuCount As Long
    '    For mnuCount = 0 To uPosition
    '        LogMessage "SAMenu item " & Format(mnuCount) & " is " & _
    '                    GetMenuName(hMenu, mnuCount)
    '    Next mnuCount
    '    With fMainForm.ATB.Bands(hMenuID)
    '        Dim myTool As SAToolbarTool
    '        For Each myTool In .Tools
    '            LogMessage "VBMenu item " & myTool.Name
    '        Next myTool
    '    End With
    'End If
    Resume Next
 
End Function

Public Function Do_Check_Menu_Proc(ByVal hMenu As Long, _
                                 ByVal uPosition As Long, _
                                 ByVal uFlags As Long _
                                 ) As Long
Dim lButtonID As Long
Dim aButtonTool As SAToolbarTool
Dim objTopTool As SAToolbarTool
Dim objTool As SAToolbarTool
Dim Band As SAToolbarBand
Dim strKey As String
Dim strToolKey As String
Dim lIdx As Long

    If CmdLineNoMenu Then Exit Function
    
    '''''If DisableCount = 0 Then
    '''''    LogMessage "Check_Menu_Proc - menu redraw not disabled"
    '''''End If
    
    If Not bCheckMenuHandle(SAShMenu, hMenu) Then Exit Function  ' not for us.
    
    Dim Id As String
    Dim idNum As Long
    Id = SSFullGetMenuID(hMenu, uPosition, uFlags)
    If Id = SA_VB_EmptyString Then Exit Function
    If Left(Id, 6) = "SAIDM_" Then 'DEV_STRING
        idNum = val(Mid$(Id, 7))
    Else
        idNum = 0
    End If

    bMenusChanged = True    ' flag for updating
    
    On Error GoTo MenuError
    fMainForm.SSAtbUpdating = True
    
    
    If IsDrawingTool(idNum) And (uFlags And MF_CHECKED) <> 0 Then
        ' uncheck all root popups and all children
        Set Band = fMainForm.ATB.Bands(strDrawMenu)
        If Not Band Is Nothing Then
            Band.UncheckAll True, False, 2
        End If
        Set Band = fMainForm.ATB.Bands(sToolboxBand)
        If Not Band Is Nothing Then
            Band.UncheckAll True, False, 2
        End If
    End If
    
    Set objTool = fMainForm.ATB.Tools(Id)
    
    If IsDrawingTool(idNum) And (uFlags And MF_CHECKED) <> 0 Then
        ' update draw popup button image
        ' firstly do the draw menu
        Set Band = fMainForm.ATB.Bands(strDrawMenu)
        If Not Band Is Nothing And Not objTool Is Nothing Then
            ' This is to make the menu system update the root tool properly when picking from popup
            If g_strLastDrawRootPopupToolName <> "" Then
                Set objTopTool = Band.Tools(g_strLastDrawRootPopupToolName)
                If Not objTopTool Is Nothing Then
                    ' Only do this for drawing tools..?not sure why I decided that
                    If IsDrawingTool(objTopTool.toolID) Then
                        objTopTool.CopyPicture objTool
                        objTopTool.ExecCommandID = idNum
                        'objTopTool.Checked = True ' didn't 'take'
                        objTopTool.Checked2 True, True ' updates root
                    Else
                        objTopTool.CopyPicture objTool ' since we update the others on doing the toolbox
                        ' I think this gets updated anyway, but this works
                    End If
                End If
            Else
                Set objTopTool = Nothing
                Set aButtonTool = Band.FindToolInSubBands(objTool.name, objTopTool)
                If Not objTopTool Is Nothing And Not objTopTool Is aButtonTool Then
                    ' Only do this for drawing tools..?not sure why I decided that
                    If IsDrawingTool(objTopTool.toolID) Then
                        objTopTool.CopyPicture objTool
                        objTopTool.ExecCommandID = idNum
                        'objTopTool.Checked = True ' didn't 'take'
                        objTopTool.Checked2 True, True ' updates root
                    Else
                        objTopTool.CopyPicture objTool ' since we update the others on doing the toolbox
                        ' I think this gets updated anyway, but this works
                    End If
                End If
            End If
        End If
        ' then do the draw toolbox
        Set Band = fMainForm.ATB.Bands(sToolboxBand)
        If Not Band Is Nothing And Not objTool Is Nothing Then
            ' This is to make the menu system update the root tool properly when picking from popup
            If g_strLastDrawRootPopupToolName <> "" Then
                Set objTopTool = Band.Tools(g_strLastDrawRootPopupToolName)
                If Not objTopTool Is Nothing Then
                    objTopTool.CopyPicture objTool
                    objTopTool.ExecCommandID = idNum
                    'objTopTool.Checked = True ' didn't 'take'
                    objTopTool.Checked2 True, True ' updates root
                End If
            Else
                Set objTopTool = Nothing
                Set aButtonTool = Band.FindToolInSubBands(objTool.name, objTopTool)
                If Not objTopTool Is Nothing And Not objTopTool Is aButtonTool Then
                    objTopTool.CopyPicture objTool
                    objTopTool.ExecCommandID = idNum
                    'objTopTool.Checked = True ' didn't 'take'
                    objTopTool.Checked2 True, True ' updates root
                End If
            End If
        End If
        ' Now we are finished with this..
        g_strLastDrawRootPopupToolName = ""
    End If
    
    If (uFlags And MF_CHECKED) <> 0 Then
        ' we need to set up the drop down button
        On Error Resume Next
        lButtonID = dicStereoDrawTools(GetActiveDiagramType() & GetUserMode() & Id)
        On Error GoTo MenuError
        If lButtonID <> 0 Then ' try to set up the drop down button
            strToolKey = "TB_" & Format(lButtonID)
            strKey = "TB_" & GetActiveDiagramType() & GetUserMode() & strToolKey
            strToolKey = strKey
            
            ' firstly do the draw menu
            Set Band = fMainForm.ATB.Bands(strDrawMenu)
            Set aButtonTool = Band.Tools(strToolKey) 'DEV_STRING
            If aButtonTool Is Nothing Then
                Set aButtonTool = Band.FindToolInSubBands(strToolKey, objTopTool)
                ' doesn't have consistent results
                'If Not objTopTool Is Nothing Then ' update root popup tool
                '    'objTopTool.Style = SATB_ST_Text
                '    'objTopTool.ClearPicture
                '    'Set objTopTool = fMainForm.ATB.Tools(objTopTool.name) 'DEV_STRING
                '    objTopTool.CopyPicture objTool
                '    objTopTool.ToolTipText = objTool.ToolTipText
                '    objTopTool.Caption = objTool.Caption
                '    objTopTool.ExecCommandID = idNum
                '    objTopTool.Checked = True
                'End If
            End If
            ' Can optionally clear the picture in case the tool being copied has none...but we then don't get the caption back on its own even if we set the Style later on
            'aButtonTool.Style = SATB_ST_Text
            'aButtonTool.ClearPicture
            aButtonTool.CopyPicture objTool
            aButtonTool.ToolTipText = objTool.ToolTipText
            aButtonTool.Caption = objTool.Caption
            aButtonTool.ExecCommandID = idNum
            CheckMenuTool aButtonTool, True
            
            ' then the toolbar
            Set Band = fMainForm.ATB.Bands(sToolboxBand)
            Set aButtonTool = Band.Tools(strToolKey) 'DEV_STRING
            If aButtonTool Is Nothing Then
                Set aButtonTool = Band.FindToolInSubBands(strToolKey, objTopTool)
                ' doesn't have consistent results
                'If Not objTopTool Is Nothing Then ' update root popup tool
                '    'objTopTool.Style = SATB_ST_Text
                '    'objTopTool.ClearPicture
                '    'Set objTopTool = fMainForm.ATB.Tools(objTopTool.name) 'DEV_STRING
                '    objTopTool.CopyPicture objTool
                '    objTopTool.ToolTipText = objTool.ToolTipText
                '    objTopTool.Caption = objTool.Caption
                '    objTopTool.ExecCommandID = idNum
                '    objTopTool.Checked = True
                'End If
            End If
            'aButtonTool.Style = SATB_ST_Text
            'aButtonTool.ClearPicture
            aButtonTool.CopyPicture objTool
            aButtonTool.ToolTipText = objTool.ToolTipText
            aButtonTool.Caption = objTool.Caption
            aButtonTool.ExecCommandID = idNum
            CheckMenuTool aButtonTool, True

' TODO TOOLBAR - Uncomment and fix this so it remembers the last stereotype tool chosen (when the tool was not selected) when flipping diagrams
' TODO TOOLBAR - it makes tools disappear when flipping diagrams at present?? - CR20660
'            On Error Resume Next
'                fMainForm.ActiveForm.collTBSubs.Remove aButtonTool.Name
'                fMainForm.ActiveForm.collTBSubs.Add idNum, aButtonTool.Name
'            On Error GoTo MenuError
        
            Set aButtonTool = fMainForm.ATB.Tools(strToolKey) 'DEV_STRING
            aButtonTool.Checked = True
            ' Can optionally set the caption and tooltip of the toolbar button here
            ' This leaves an inconsistency where there is more than one represented type as the first option will have the caption of the symbol type and not the definition type
            'aButtonTool.ToolTipText = objTool.ToolTipText
            'aButtonTool.Caption = objTool.Caption

            ' While this covers the re-selection of the active drawing tool on switching diagram, it prevents you from having a different stored active tool for the same control on different diagrams
            'This is why it is done against the precise popup tools, above
            'CheckMenuTool fMainForm.ATB.Tools(strKey), True ' the popup tool, wherever it is, can be a stereotype popup
        End If
        
        ' and finally check it - note the popup tools are done above
        objTool.Checked = True
        ' This covers the re-selection of the active drawing tool on switching diagram without side-effect
        CheckMenuTool objTool, True ' the leaf tool which could be a stereotype
        'logmessage "Check_Menu_Proc tool:" & ID & " checked"
    Else
        objTool.Checked = False
        CheckMenuTool objTool, False ' observed Diagram Auto-routing submenu options in a bad state without calling this; 2 options ticked when there should be only 1
        ' we need to set up the drop down button
        On Error Resume Next
        lButtonID = dicStereoDrawTools(GetActiveDiagramType() & GetUserMode() & Id)
        On Error GoTo MenuError
        If lButtonID <> 0 Then ' try to set up the drop down button
            fMainForm.ATB.Tools("TB_" & GetActiveDiagramType() & GetUserMode() & "TB_" & Format(lButtonID)).Checked = False 'DEV_STRING
        End If
    End If
    If idNum = 355 Then
        fMainForm.ATB.Tools("id_SymbolDepictions").Checked = objTool.Checked
    End If
    fMainForm.SSAtbUpdating = False
    On Error GoTo 0
        
    Exit Function
    
MenuError:
    On Error GoTo 0
    
    LogMessage "Check_Menu_Proc ERROR " & Id & _
        " flags:" & Hex(uFlags) & " hMenu,pos:" & Hex(hMenu) & "," & Format(uPosition) _
        & " GethMenuID:" & GethMenuID(SAShMenu, hMenu) 'DEV_STRING
    
    Resume Next
 
End Function

Public Function Do_Enable_Menu_Proc(ByVal hMenu As Long, _
                                 ByVal uPosition As Long, _
                                 ByVal uFlags As Long _
                                 ) As Long
    Dim objParentBand As SAToolbarBand
    Dim objTool As SAToolbarTool
    
    Do_Enable_Menu_Proc = uFlags
    
    If CmdLineNoMenu Then Exit Function
    
    If Not bCheckMenuHandle(SAShMenu, hMenu) Then Exit Function  ' not for us.
    
    Dim Id As String
    Id = SSFullGetMenuID(hMenu, uPosition, uFlags)
    If Id = SA_VB_EmptyString Then Exit Function

    bMenusChanged = True    ' flag for updating

    On Error GoTo MenuError
    fMainForm.SSAtbUpdating = True
    If (uFlags And (MF_DISABLED Or MF_GRAYED)) <> 0 Then
'        fMainForm.ATB.Tools(id).Enabled = False
        On Error Resume Next
        Set objTool = fMainForm.ATB.Tools(Id)
        On Error GoTo 0
        If Not objTool Is Nothing Then
            EnableMenuTool objTool, False
            
            If IsDrawingTool(objTool.toolID) Then
                ' It is a drawing tool so we need to see if the parent band of stereotypes need greying
                Set objParentBand = GetDrawingStereoTypeBand(GetActiveDiagramType() & GetUserMode() & Id)
                If Not objParentBand Is Nothing Then
                    EnableMenuTool fMainForm.ATB.Tools(objParentBand.BandName), False
                End If
            End If
        End If
    Else
'        fMainForm.ATB.Tools(id).Enabled = True
        If Not EnableMenuTool(fMainForm.ATB.Tools(Id), True) Then
            ' Enable request failed
            Do_Enable_Menu_Proc = uFlags Or MF_GRAYED
        End If
    End If
    fMainForm.SSAtbUpdating = False
    On Error GoTo 0
        
    Exit Function

MenuError:
    On Error GoTo 0
    
    LogMessage "Enable_Menu_Proc ERROR " & Id & _
        " flags:" & Hex(uFlags) & " hMenu,pos:" & Hex(hMenu) & "," & Format(uPosition) _
        & " GethMenuID:" & GethMenuID(SAShMenu, hMenu) 'DEV_STRING
    
    Resume Next
 
 End Function

Public Function Do_Show_Menu_Proc(ByVal hMenu As Long, _
                                 ByVal uPosition As Long, _
                                 ByVal bShow As Boolean _
                                 ) As Long
    Dim uFlags As Long
    
    If CmdLineNoMenu Then Exit Function
    
    If Not bCheckMenuHandle(SAShMenu, hMenu) Then Exit Function  ' not for us.
    
    Dim Id As String
    Id = SSFullGetMenuID(hMenu, uPosition, uFlags)
    If Id = SA_VB_EmptyString Then Exit Function
    If Id = TOOL_DRAWMENU Then
        Id = strDrawMenu
    End If

    bMenusChanged = True    ' flag for updating

    On Error GoTo MenuError
    fMainForm.SSAtbUpdating = True
    
    ShowMenuTool fMainForm.ATB, fMainForm.ATB.Tools(Id), bShow
    
    fMainForm.SSAtbUpdating = False
    On Error GoTo 0
        
    Exit Function

MenuError:
    On Error GoTo 0
    
    LogMessage "Show_Menu_Proc ERROR " & Id & _
        " bshow:" & CStr(bShow) & " hMenu,pos:" & Hex(hMenu) & "," & Format(uPosition) _
        & " GethMenuID:" & GethMenuID(SAShMenu, hMenu) 'DEV_STRING
    
    Resume Next
 
 End Function

' this function checks to see if a given hMenu is a sub menu of the top menu
Private Function bCheckMenuHandle(ByVal hTopMenu As Long, ByVal hMenu As Long) As Boolean
    Dim lSubCount As Long, lSubId As Long, hSubMenu As Long
    Dim i As Long
    
    If hTopMenu = hMenu Then
        bCheckMenuHandle = True
        Exit Function
    End If
    
    bCheckMenuHandle = False ' assume not a sub menu
    
    ' for each item in hTopMenu
    lSubCount = GetMenuItemCount(hTopMenu)
    If lSubCount = 0 Then Exit Function
    For i = 0 To lSubCount - 1
        hSubMenu = GetSubMenu(hTopMenu, i)
        lSubId = GetMenuItemID(hTopMenu, i)
        If lSubId < 0 Then
            bCheckMenuHandle = bCheckMenuHandle(hSubMenu, hMenu)
            If bCheckMenuHandle Then Exit For
        End If
    Next i
End Function

'given the hMenu, uPosition and uFlags return the SSActiveToolbars ID
'Menucountposition is for diagnostics
Private Function SSFullGetMenuID(ByVal hMenu As Long, _
                                 ByVal uPosition As Long, _
                                 ByVal uFlags As Long _
                                 ) As String
    Dim lID As Long
    If (uFlags And MF_BYPOSITION) <> 0 Then
        ' oops this could be hard
        lID = GetMenuItemID(hMenu, uPosition)
    Else
        lID = uPosition
    End If
    
    If lID = -1 Then
        Dim sName As String
        sName = GetMenuName(hMenu, uPosition)
        
        SSFullGetMenuID = "id_" & CleanMenuID(sName) 'DEV_STRING
        
    Else
        SSFullGetMenuID = SSGetMenuID(lID)
    End If

End Function

' given a numeric ID return the ID that is used in the ActiveToolbar
Public Function SSGetMenuID(Id As Long) As String
    Select Case Id
        Case 252           ' 252 = IDMDUMMYINSERT
            SSGetMenuID = SA_VB_EmptyString    ' not used any more.
        Case Else
            
            SSGetMenuID = "SAIDM_" & Format(Id) 'DEV_STRING
            
    End Select
End Function

' Given a band name, an index and a tool (from the main tools collection)
' This performs the insert and marks it as inserted
' The tool supplied MUST be from the main tools collection - or the flag will not be set correctly
Public Function InsertInTools(ByVal r_strBandName As String, ByVal v_lngIndex As Long, ByRef r_objTool As SAToolbarTool)
    r_objTool.Visible = False
    ShowMenuTool fMainForm.ATB, r_objTool.name, True    ' Delay showing of item until timer
    
    fMainForm.ATB.Bands(r_strBandName).Tools.Insert v_lngIndex, r_objTool
    If r_strBandName = SAXRes.GetLocalString(IDS_uloc_____mainmenu) Then
        r_objTool.Category = SAXRes.GetLocalString(IDS_DsgnT_ToolbarMainMenuCategoryText____mainmenu)
    End If
    If r_objTool.Category <> SAXRes.GetLocalString(IDS_sa2001menuprc_____customized) Then
        ' The tool is not a customized tool (customized tools are drawing tools like "Popkin 1" or user symbols)
        ' Customized tools are special and are never marked as being in the menu
        ' This allows the draw menu/toolbar code to always insert them
        r_objTool.UpdateFlags = r_objTool.UpdateFlags Or MENUTOOL_INSERTEDINMENU
    End If
End Function

Public Function InsertInMenuExt(ATB As SAToolbar, _
                              cband As SAToolbarBand, _
                              IDat As String, _
                              TooltoInsert As SAToolbarTool, _
                              Optional bInsertAtStart As Boolean = True, _
                              Optional bAfterSeparator As Boolean = False, _
                              Optional bForceInsert As Boolean) As Boolean
    
    Dim objTool As SAToolbarTool
    
    If CmdLineToolCheck Then
        ' Ignore the MENUTOOL_INSERTEDINMENU flag is we are doing a toolcheck
        ' we WILL insert if it does not exist in the tools for that band!!
        On Error Resume Next
        Set objTool = Nothing
        Set objTool = cband.Tools(TooltoInsert.name)
        If objTool Is Nothing Then
            bForceInsert = True
        End If
        On Error GoTo 0
    End If
    
    If Not bForceInsert Then
        If ToolInMasterCollection(TooltoInsert.name, objTool) Then
            If 0 <> (objTool.UpdateFlags And MENUTOOL_INSERTEDINMENU) Then
                InsertInMenuExt = True
#If TOOLDEBUGGING Then
                Call LogMessageTools("MenuPrc-InsertInMenuExt- Show tool '" & TooltoInsert.name & "'") 'DEV_STRING
#End If
                ShowMenuTool fMainForm.ATB, objTool, True
                
                Exit Function   ' The tool already exists so abort - success
            End If
        End If
    End If
    
    Set objTool = ATB.Tools(TooltoInsert.name)
    If IDat = SA_VB_EmptyString Then ' Insert at start or end of menu
        ' got it
        If bInsertAtStart Then
            InsertInTools cband.BandName, 0, TooltoInsert
        Else
            InsertInTools cband.BandName, -1, TooltoInsert
        End If
        InsertInMenuExt = True
        objTool.UpdateFlags = objTool.UpdateFlags Or MENUTOOL_INSERTEDINMENU
    Else  ' Do the search insert
        InsertInMenuExt = InsertInMenu(ATB, cband, IDat, TooltoInsert, bAfterSeparator)
        If InsertInMenuExt Then
            ''' TODO DECOUPLE - should this always be set - what happens if an insert fails - should we find another menu?
            objTool.UpdateFlags = objTool.UpdateFlags Or MENUTOOL_INSERTEDINMENU
        Else
            If CmdLineQAReporting Then
                SAMessageBox "InsertInMenuExt failed to insert menu item '" & TooltoInsert.name & "' into band '" & cband.BandName & "'" & vbCrLf & "This could be an error." 'DEV_STRING
            End If
        End If
    End If
    ShowMenuTool fMainForm.ATB, objTool, True
End Function

' finds IDat in cTools - or one of the children of cTools and inserts IDToInsert before IDat
' Since Decoupling - this is only called if the item was not already in the menu system,
Private Function InsertInMenu(ATB As SAToolbar, _
                              cband As SAToolbarBand, _
                              IDat As String, _
                              TooltoInsert As SAToolbarTool, _
                              Optional bAfterSeparator = False) As Boolean
    InsertInMenu = False ' assume failure
    Dim ThisTool As SAToolbarTool
    Dim i As Long
              
    For i = 0 To cband.Tools.Count - 1
        Set ThisTool = cband.Tools(i)
        If ThisTool.name = IDat Then
            ' got it
            InsertInTools cband.BandName, i, TooltoInsert ' Insert the tool
            
            If bAfterSeparator Then
                ' We may need to move the separator
                If 0 <> (ThisTool.UpdateFlags And MENUTOOL_SEPARATOR) Then
                    ' The tool we are inserting before has a separator
                    Call SetToolSeparator(ThisTool, False) ' Remove the separator
                    Call SetToolSeparator(cband.Tools(i), True) ' Add the separator before the new item
                End If
            End If
            
            InsertInMenu = True
            Exit Function
        ElseIf ThisTool.SubBandName <> SA_VB_EmptyString Then
            If InsertInMenu(ATB, ATB.Bands(ThisTool.SubBandName), IDat, TooltoInsert) Then
                InsertInMenu = True
                Exit Function
            End If
        End If
    Next i
End Function

Private Function InsertAnywhereAfter(ByVal v_strToolName As String, ByVal v_strAfterName As String) As Boolean
    ' Since customizable bands allow tools to be moved
    
    Dim objBands As SAToolbarBands
    Dim objTools As SAToolbarTools
    Dim objBand As SAToolbarBand
    Dim objTool As SAToolbarTool
    Dim objToolIns As SAToolbarTool
    Dim lNdx As Long
    Dim bRet As Boolean
    
    On Error Resume Next
    Set objToolIns = fMainForm.ATB.Tools(v_strToolName)
    On Error GoTo 0
    If objToolIns Is Nothing Then Exit Function
    Set objBands = fMainForm.ATB.Bands
    For Each objBand In objBands
        Set objTools = objBand.Tools
        For lNdx = objTools.Count - 1 To 0 Step -1
            Set objTool = objTools(lNdx)
            If objTool.name = v_strAfterName Then
                objTools.Add objToolIns.toolID, v_strToolName, True, , , lNdx
            End If
        Next
    Next
End Function

' finds ToolName in cTools and in menu and removes it (or hides it)
' This should ONLY be called when really necessary
' Normally one should use ShowMenuTool - as this works off the timer
' NOTES ON v_blnForceTotalRemove :-
' This is used only for macro item and does NOT remove the item
' from the MASTER tools collection. Doing this would lose valuable information about
' the macro item on, unloading and reloading the macro project associated with the tool.
' E.g. MENUTOOL_INSERTEDINMENU flag. This would result in duplicate items when the
' project was reloaded.
Public Sub DoRemoveOrHideTool(ATB As SAToolbar, ToolName As String, Optional ByVal v_blnForceTotalRemove As Boolean, Optional v_blnSuppressTBCode As Boolean = False)
    Dim ThisTool As SAToolbarTool
    Dim SubTool As SAToolbarTool
    Dim ThisBand As SAToolbarBand
    Dim lngButtonID As Long
    Dim blnRemoveBand As Boolean
    Dim lngBandPos As Long
    Dim lngToolPos As Long
    
    On Error GoTo ErrExit
    bInhibitMenuTimer = True
    
    ' Process all bands and tools to ensure the tool is got everywhere
    For lngBandPos = ATB.Bands.Count - 1 To 0 Step -1
        Set ThisBand = ATB.Bands(lngBandPos)
        For lngToolPos = ThisBand.Tools.Count - 1 To 0 Step -1
            Set ThisTool = ThisBand.Tools(lngToolPos)
            If ThisTool.name = ToolName Then
                ' got it
                If IsDrawingTool(ThisTool.toolID) _
                Or dicDrawPopupsByTypeModeName.Exists(ThisTool.name) Then
                    If ThisBand.BandName = BAND_DRAWMENU Or _
                        dicDrawPopupsByTypeModeName.Exists(ThisBand.BandName) Or _
                        ThisBand.BandName = BAND_DRAWLINEMENU Or _
                        ThisBand.BandName = BAND_DRAWNODEMENU Or _
                        ThisBand.BandName = sToolboxBand Or Left(ThisBand.BandName, 3) = "TB_" Then 'DEV_STRING
                        ' Drawing tools must only be removed from the draw menu and draw toolbar
                        ' This is a destroyable drawing tool
#If TOOLDEBUGGING Then
                        Call LogMessageTools("MenuPrc-DoRemoveOrHideTool- Remove drawing tool '" & ToolName & "'") 'DEV_STRING
#End If
                        ThisBand.Tools.Remove ToolName
                    Else
                        ' Drawing tools anywhere else in the menu are simply grayed
#If TOOLDEBUGGING Then
                        Call LogMessageTools("MenuPrc-DoRemoveOrHideTool- Disabling custom tool '" & ToolName & "'") 'DEV_STRING
#End If
                        ThisBand.Tools(ThisTool.name).Enabled = False   ' Disable this tool immediately
' can't do this because tools which are removed from the master tools collection don't get processed in the menu timer - EnableMenuTool ThisTool, False  ' Disable this tool
                    End If
                    
                    If Left(ThisBand.BandName, 3) = "TB_" And Not v_blnSuppressTBCode Then 'DEV_STRING
                        ' This tool is in a temporary/stereotype band - remove item from stereo tools collection
                        On Error Resume Next
                        lngButtonID = dicStereoDrawTools(GetActiveDiagramType() & GetUserMode() & ThisTool.name)
                        On Error GoTo ErrExit
                        If lngButtonID <> 0 Then      ' this is actually in a sub menu (stereotype)
                            dicStereoDrawTools.Remove GetActiveDiagramType() & GetUserMode() & ThisTool.name
                        End If
                        If ThisBand.Tools.Count = 0 Then
                            blnRemoveBand = True
                            Exit For    ' Nothing else to do in this band - it will be destroyed soon
                        End If
                    End If
                ElseIf v_blnForceTotalRemove Or Left(ThisTool.name, 3) = "TB_" Then 'DEV_STRING get rid of all the TB temporary tools
#If TOOLDEBUGGING Then
                    LogMessageTools "DoRemoveOrHideTool - removing tool - " & ThisTool.name & " - Force = " & CStr(v_blnForceTotalRemove) 'DEV_STRING
#End If
                    ThisBand.Tools.Remove ToolName
                Else
#If TOOLDEBUGGING Then
                    Call LogMessageTools("MenuPrc-DoRemoveOrHideTool- Hide tool '" & ToolName & "'") 'DEV_STRING
#End If
                    ThisTool.Visible = False    '' TODO DECOUPLE - not required? could optimise
                End If
            End If
        Next
        If blnRemoveBand Then
            ' This band is temporary and has been marked for destruction
#If TOOLDEBUGGING Then
            LogMessageTools "DoRemoveOrHideTool - removing band - " & ThisBand.BandName & " calling DoRemoveOrHideTool recursively" 'DEV_STRING
#End If
            blnRemoveBand = False
            DoRemoveOrHideTool ATB, ThisBand.BandName  ' ensure the parent tool is removed
#If TOOLDEBUGGING Then
            LogMessageTools "DoRemoveOrHideTool - removing band - " & ThisBand.BandName & " returned from call to DoRemoveOrHideTool" 'DEV_STRING
#End If
        End If
    Next
    
    ' Now deal with the master tools collection
    For lngToolPos = ATB.Tools.Count - 1 To 0 Step -1
        Set ThisTool = ATB.Tools(lngToolPos)
        If ThisTool.name = ToolName Then
            ' got it
            If Left(ThisTool.name, 3) = "TB_" Then   'DEV_STRING get rid of all the TB temporary tools
                If Not ATB.Bands(ThisTool.name) Is Nothing Then
#If TOOLDEBUGGING Then
                    Call LogMessageTools("MenuPrc-DoRemoveOrHideTool- Remove TB_ band and subtools from tools - '" & ToolName & "'") 'DEV_STRING
#End If
                    On Error Resume Next
                    ATB.Bands(ThisTool.name).Tools.RemoveAll
                    ATB.Bands.Remove ThisTool.name
                    On Error GoTo ErrExit
                End If
#If TOOLDEBUGGING Then
                Call LogMessageTools("MenuPrc-DoRemoveOrHideTool- Remove actual TB_ from tools - '" & ToolName & "'") 'DEV_STRING
#End If
                ATB.Tools.Remove ThisTool.name
            ElseIf dicDrawPopupsByTypeModeName.Exists(ThisTool.name) Then
                If Not ATB.Bands(ThisTool.name) Is Nothing Then
#If TOOLDEBUGGING Then
                    Call LogMessageTools("MenuPrc-DoRemoveOrHideTool- Remove TB_ band and subtools from tools - '" & ToolName & "'") 'DEV_STRING
#End If
                    On Error Resume Next
                    ATB.Bands(ThisTool.name).Tools.RemoveAll
                    ATB.Bands.Remove ThisTool.name
                    On Error GoTo ErrExit
                End If
            
                ATB.Tools.Remove ThisTool.name
            ElseIf IsDrawingTool(ThisTool.toolID) Then
                If ThisTool.Category = SAXRes.GetLocalString(IDS_sa2001menuprc_____customized) Then
                    ' Customized tools (i.e. Popkin/User symbols) must not be removed from the main tools collection during operation
#If TOOLDEBUGGING Then
                    Call LogMessageTools("MenuPrc-DoRemoveOrHideTool- Disable customized drawing tool from tools - '" & ToolName & "'") 'DEV_STRING
#End If
                    EnableMenuTool ThisTool, False
                Else
                    ' This is an ordinary destroyable drawing tool
#If TOOLDEBUGGING Then
                    Call LogMessageTools("MenuPrc-DoRemoveOrHideTool- Remove drawing tool from tools - '" & ToolName & "'") 'DEV_STRING
#End If
                    ATB.Tools.Remove ThisTool.name
                End If
            Else
#If TOOLDEBUGGING Then
                Call LogMessageTools("MenuPrc-DoRemoveOrHideTool- Hide tool from tools -'" & ToolName & "'") 'DEV_STRING
#End If
                ThisTool.Visible = False
            End If
            
            ThisTool.UpdateFlags = ThisTool.UpdateFlags And (Not MENUTOOL_VISIBLEMASK)  ' Ensure no pending visibility flags are set
            Exit For
        End If
    Next

ErrExit:
    bInhibitMenuTimer = False
    bMenusChanged = True
End Sub

' given a starting menu handle and a target menu handle, scans the starting menu
' and all children for the target menu handle. If found then returns
' the id name of the target menu
Private Function GethMenuID(hMainMenu As Long, hMenu As Long, Optional bDrawMenu As Boolean = False) As String
    Dim lSubCount As Long, sSubName As String, hSubMenu As Long, i As Long, uFlags As Long
    Dim Band As SAToolbarBand
    ' we need to navigate the main menu looking for the hMenu and returning the menuID
    GethMenuID = SA_VB_EmptyString
    ' This API function returns the number of menu items in a menu
    lSubCount = GetMenuItemCount(hMainMenu)
    If lSubCount = 0 Then Exit Function
    For i = 0 To lSubCount - 1
        ' This API function returns the handle of a menu item, given its parent's position
        hSubMenu = GetSubMenu(hMainMenu, i)
        If hSubMenu = hMenu Then
            ' got it
            sSubName = GetMenuName(hMainMenu, i)
            'logmessage "GethMenuID sSubName is " & sSubName
            
            GethMenuID = "id_" & CleanMenuID(sSubName) 'DEV_STRING
            If bDrawMenu Then
                On Error Resume Next
                Set Band = fMainForm.ATB.Bands(GethMenuID)
                On Error GoTo 0
                If Band Is Nothing Then
                    GethMenuID = "id_" & GetActiveDiagramType() & GetUserMode() & CleanMenuID(sSubName) 'DEV_STRING
                End If
            End If
            Exit Function
        Else
            Dim lSubId As Long
            lSubId = GetMenuItemID(hMainMenu, i)
            If lSubId < 0 Then
                sSubName = GetMenuName(hMainMenu, i)
                sSubName = CleanMenuID(sSubName)
                If hMainMenu = SAShMenu Then
                    If sSubName = BAND_DRAWTOOLBOX Then
                        GethMenuID = GethMenuID(hSubMenu, hMenu, True)
                    Else
                        GethMenuID = GethMenuID(hSubMenu, hMenu, bDrawMenu)
                    End If
                ElseIf Not hMainMenu = SAShMenu And (sSubName = "DrawLine" Or sSubName = "DrawNode") Then
                    GethMenuID = GethMenuID(hSubMenu, hMenu, True)
                Else
                    GethMenuID = GethMenuID(hSubMenu, hMenu, bDrawMenu)
                End If
                If GethMenuID <> SA_VB_EmptyString Then Exit Function
            End If
        End If
    Next i
End Function

' wrapper to make it easy to switch algorithms when needed
Private Sub SynchronizeMenu(ATB As SAToolbar, cband As String, hMenu As Long)
    SynchronizePopupMenuDecouple ATB, cband, hMenu
End Sub

Public Sub Do_SynchronizeMainMenu()
    If CmdLineNoMenu Then Exit Sub
    
    If bToolBoxExists Then
        RemoveDrawToolBox
    End If

    
    SynchronizeMenu fMainForm.ATB, SAXRes.GetLocalString(IDS_uloc_____mainmenu), SAShMenu  ' Sync the main menu
    
    
    ' Ensure VBA knows the whole menu has been re-jigged - and let VBA add its items again
    SAAppObj.AppEvent_MainMenuUpdate
    SAAppObj.AppEvent_ToolsMenuUpdate
    SAAppObj.AppEvent_MethodMenuUpdate
    SAAppObj.AppEvent_ReportsMenuUpdate
    
    If Not CmdLineNoRedraw Then fMainForm.ATB.RecalcLayout
End Sub

' synchronizes the states of all hMenu items and children with the Toolbar system
' only adds items or processes separator information, if the tools were NOT already
' present
Private Sub SynchronizePopupMenuDecouple(ATB As SAToolbar, cband As String, hMenu As Long)
    Dim lSubCount As Long, sSubName As String, sSubName2 As String, hSubMenu As Long, i As Long
    Dim sSubId As String, lSubId As Long, bPopup As Boolean
    Dim abToolItem As SAToolbarTool, bSeparator As Boolean
    Dim uIDUse As Long
    Dim menuFlags As Long
    Dim blnNewTool As Boolean
    Dim objTool As SAToolbarTool
    Dim objBand As SAToolbarBand

    ' for each item in hMenu
    lSubCount = GetMenuItemCount(hMenu)
    If lSubCount = 0 Then Exit Sub
    For i = 0 To lSubCount - 1
        hSubMenu = GetSubMenu(hMenu, i)

        sSubName = GetMenuName(hMenu, i)
        
        lSubId = GetMenuItemID(hMenu, i)
        
        menuFlags = GetMenuState(hMenu, i, MF_BYPOSITION)
                
        
        If sSubName = SA_VB_EmptyString And lSubId = 0 Then
            sSubName = "separator" 'DEV_STRING
            sSubId = "separator" 'DEV_STRING
            bPopup = False
        ElseIf lSubId < 0 Then
            sSubName2 = CleanMenuID(sSubName)
            sSubId = "id_" & sSubName2 'DEV_STRING
            On Error Resume Next
            Set objBand = Nothing
            Set objBand = fMainForm.ATB.Bands(sSubId)
            On Error GoTo 0
            If objBand Is Nothing Then
                sSubId = "id_" & GetActiveDiagramType() & GetUserMode() & sSubName2 'DEV_STRING
            End If
            bPopup = True
        Else
            sSubId = SSGetMenuID(lSubId)
            bPopup = False
        End If
        
        If sSubId = "separator" Then 'DEV_STRING
            bSeparator = True
        Else
            If bPopup Then
              uIDUse = -1   ' Popup item - use generated ID
            Else
              uIDUse = lSubId   ' Not Popup item - use the given ID
            End If
            
            If CmdLineToolCheck Then
                ' The toolcheck version ALLOWS caption overwrite for US English - this enables us to capture missing captions
                Dim strLocale As String
                XResObj.GetLocale strLocale
                If strLocale <> "409" Then      'DEV_STRING
                    sSubName = ""   ' If this is not US English then ensure the caption is not altered  'DEV_STRING
                End If
            Else
                sSubName = ""       ' We do NOT use the caption from the popup this will destroy the localized caption  'DEV_STRING
            End If
            
            blnNewTool = CheckAddTool(ATB, bPopup, uIDUse, sSubId, sSubName)
            
            ' Sort out the state flags
            Set objTool = fMainForm.ATB.Tools(sSubId)
            If (menuFlags And MF_CHECKED) <> 0 Then
                objTool.Checked = True
            Else
                objTool.Checked = False
            End If
            If (menuFlags And (MF_DISABLED Or MF_GRAYED)) <> 0 Then
                EnableMenuTool objTool, False
            Else
                EnableMenuTool objTool, True
            End If
            
            If blnNewTool Then
                ' Insert the tool - only if it was not already in the toolbar system
                InsertInTools cband, -1, objTool
            End If
            
            If cband = strDrawMenu Then 'DEV_STRING
                TryAddDrawMenuItemToDrawSubMenu sToolboxBand, lSubId, (menuFlags And MF_CHECKED), bSeparator, False ' no way of knowing if this is a sub type.
            End If
            
            If blnNewTool And bSeparator Then
                ' Only update the separator information if the tool was not already in the toolbar system
                bSeparator = False
                Call SetToolSeparator(ATB.Bands(cband).Tools(sSubId), True)
            End If
                        
#If TOOLDEBUGGING Then
            Call LogMessageTools("MenuPrc-SynchronizePopupMenuDecouple- Show tool '" & sSubId & "'") 'DEV_STRING
#End If
            ShowMenuTool fMainForm.ATB, objTool, True
                        
            ' if it is a popup then
            If bPopup Then
                'recurse
                SynchronizePopupMenuDecouple ATB, sSubId, hSubMenu
            End If
        End If
        
    Next i
    Exit Sub
End Sub

Private Sub SynchronizePopupMenuDecoupleRemove(ATB As SAToolbar, cband As String, hMenu As Long, ByVal sMenuName As String)
    Dim lSubCount As Long, sSubName As String, sSubName2 As String, hSubMenu As Long, i As Long
    Dim sSubId As String, lSubId As Long, bPopup As Boolean
    Dim abToolItem As SAToolbarTool, bSeparator As Boolean
    Dim uIDUse As Long
    Dim menuFlags As Long
    Dim blnNewTool As Boolean
    Dim blnDisabled As Boolean
    Dim objBand As SAToolbarBand

#If TOOLDEBUGGING Then
    Call LogMessageTools("MenuPrc-SynchronizePopupMenuDecoupleRemove- processing menu '" & cband & "'") 'DEV_STRING
#End If

    ' for each item in hMenu
    lSubCount = GetMenuItemCount(hMenu)
    If lSubCount = 0 Then Exit Sub
    For i = 0 To lSubCount - 1
        sSubName = GetMenuName(hMenu, i)
        
        If (sMenuName = SA_VB_EmptyString) Or (("id_" & CleanMenuID(sSubName)) = sMenuName) Then 'DEV_STRING
            hSubMenu = GetSubMenu(hMenu, i)
            
            lSubId = GetMenuItemID(hMenu, i)
            
            menuFlags = GetMenuState(hMenu, i, MF_BYPOSITION)
                    
            
            If sSubName = SA_VB_EmptyString And lSubId = 0 Then
                sSubName = "separator" 'DEV_STRING
                sSubId = "separator" 'DEV_STRING
                bPopup = False
            ElseIf lSubId < 0 Then
                sSubName2 = CleanMenuID(sSubName)
                sSubId = "id_" & sSubName2 'DEV_STRING
                On Error Resume Next
                Set objBand = Nothing
                Set objBand = fMainForm.ATB.Bands(sSubId)
                On Error GoTo 0
                If objBand Is Nothing Then
                    sSubId = "id_" & GetActiveDiagramType() & GetUserMode() & sSubName2 'DEV_STRING
                End If
                bPopup = True
            Else
                sSubId = SSGetMenuID(lSubId)
                bPopup = False
            End If
            
            If sSubId = "separator" Then 'DEV_STRING
                bSeparator = True
            Else
                If bPopup Then
                  uIDUse = -1   ' Popup item - use generated ID
                Else
                  uIDUse = lSubId   ' Not Popup item - use the given ID
                End If
                
                blnDisabled = False
                If bPopup Then
                    ' This is a popup
                    If ToolInATBCollection(fMainForm.ATB.Bands(SAXRes.GetLocalString(IDS_uloc_____mainmenu)).Tools, sSubId) Then
                        ' This popup is in the main menu band - so don't hide it
#If TOOLDEBUGGING Then
                        Call LogMessageTools("MenuPrc-SynchronizePopupMenuDecoupleRemove - Disable popup tool '" & sSubId & "'") 'DEV_STRING
#End If
                        EnableMenuTool fMainForm.ATB.Tools(sSubId), False
                        blnDisabled = True
                    End If
                End If
                            
                If Not blnDisabled Then
                    ' Not disabled so hide it
#If TOOLDEBUGGING Then
                    Call LogMessageTools("MenuPrc-SynchronizePopupMenuDecouple- Hide tool '" & sSubId & "'") 'DEV_STRING
#End If
                    ShowMenuTool fMainForm.ATB, ATB.Tools(sSubId), False
                End If
                                        
                ' if it is a popup then
                If bPopup Then
                    'recurse
                    SynchronizePopupMenuDecoupleRemove ATB, sSubId, hSubMenu, SA_VB_EmptyString
                End If
            End If
            
            
            If sMenuName <> SA_VB_EmptyString Then
                Exit For
            End If
        End If
    Next i
    Exit Sub
End Sub

Private Sub UpdateToolInBands(ATB As SAToolbar, name As String, Caption As String)
    Dim abBand As SAToolbarBand
    Dim abTool As SAToolbarTool
    Dim lngIndex As Long
    
    For Each abBand In ATB.Bands
        For lngIndex = 0 To abBand.Tools.Count - 1
            Set abTool = abBand.Tools(lngIndex)
            If abTool.name = name Then
                abTool.Caption = Caption
            End If
        Next
    Next abBand
End Sub


Public Function CheckAddTool(ATB As SAToolbar, bPopup As Boolean, lSubId As Long, sSubId As String, sSubName As String, Optional sCategory As String = "General", Optional BmpFileName As String = "", Optional ByRef r_Id As Long, Optional ByRef r_objTool As SAToolbarTool, Optional ByVal v_blnDrawPopup As Boolean) As Boolean 'DEV_STRING

    Dim objBand As SAToolbarBand
    Dim abTool As SAToolbarTool
    Dim uIDUse As Long
    Dim p      As Long
    Dim s      As String
    Dim errFlag As Boolean
    Dim strCaption As String
    Dim strToolTip As String
    Dim enuType As SATOOLBAR_TOOLTYPE
    Dim lToolID As Long
    
#If TOOLDEBUGGING Then
    strLogMessageToolsPrefix = Space$(Len(strLogMessageToolsPrefix) + 1)
#End If
    
    If Not ToolInMasterCollection(sSubId, abTool) Then
        If bPopup Then
#If TOOLDEBUGGING Then
            Call LogMessageTools("MenuPrc-CheckAddTool- Adding popup tool '" & sSubId & "'") 'DEV_STRING
#End If
            If lSubId = -1 Then ' If no ID is given, then generate one
              uIDUse = ATB.GetNextInternalToolID()
            ElseIf lSubId = -2 Then ' If no ID is given, then use a macro toolid
              uIDUse = GetFreeMacroId()
            Else
              uIDUse = lSubId
            End If
            
            p = InStr(sSubName, Chr(9))
            If p > 0 Then
              s = Mid$(sSubName, 1, p - 1)
            Else
              s = sSubName
            End If
            strCaption = s
            
            p = InStr(CleanMenuPopup(sSubName), Chr(9))
            If p > 0 Then
              s = Mid$(CleanMenuPopup(sSubName), 1, p - 1)
            Else
              s = CleanMenuPopup(sSubName)
            End If
            strToolTip = s
            
            If Not BandInATBCollection(ATB.Bands, sSubId) Then
                enuType = SATB_TT_BUTTONPOPUP
                If v_blnDrawPopup Then
                    enuType = SATB_TT_BUTTONDROPDOWN
                End If
                Set objBand = ATB.Bands.Add(sSubId, SATB_BT_POPUP, uIDUse, enuType)
            Else
#If TOOLDEBUGGING Then
               Call LogMessageTools("MenuPrc-CheckAddTool- Failed Adding tool '" & sSubId & "'") 'DEV_STRING
#End If
                CheckAddTool = False
#If TOOLDEBUGGING Then
    strLogMessageToolsPrefix = Space$(Len(strLogMessageToolsPrefix) - 1)
#End If
                Exit Function
            End If
            Set abTool = ATB.Tools.Add(uIDUse, sSubId, True)
            abTool.Caption = strCaption
            abTool.ToolTipText = strToolTip
            abTool.Style = SATB_ST_Text
            abTool.Category = sCategory
            Set abTool.SubBand = objBand
            
            ' now try and get the bitmap for the tool
            On Error GoTo SymBmpError
            errFlag = False
            abTool.ClearPicture
            If BmpFileName <> SA_VB_EmptyString Then
                abTool.SetPicture BmpFileName
            Else
                errFlag = True
            End If
            On Error GoTo 0
            If Not errFlag Then
                abTool.Style = SATB_ST_Standard
            End If
            
            r_Id = uIDUse
            Set r_objTool = abTool
        Else
#If TOOLDEBUGGING Then
            Call LogMessageTools("MenuPrc-CheckAddTool- Adding tool '" & sSubId & "'") 'DEV_STRING
#End If
            On Error GoTo ToolbarError1
            If lSubId = -1 Then ' If no ID is given, then generate one
              uIDUse = ATB.GetNextInternalToolID()
            ElseIf lSubId = -2 Then ' If no ID is given, then use a macro toolid
              uIDUse = GetFreeMacroId()
            Else
              uIDUse = lSubId
            End If
            
            Set abTool = ATB.Tools.Add(uIDUse, sSubId)
            'abTool.ControlType = SATB_TT_BUTTON ' no-op
            
            p = InStr(sSubName, Chr(9))
            If p > 0 Then
              s = Mid$(sSubName, 1, p - 1)
            Else
              s = sSubName
            End If
            abTool.Caption = s
            
            p = InStr(CleanMenuPopup(sSubName), Chr(9))
            If p > 0 Then
              s = Mid$(CleanMenuPopup(sSubName), 1, p - 1)
            Else
              s = CleanMenuPopup(sSubName)
            End If
            abTool.ToolTipText = s
            
            
            abTool.Category = sCategory
            If IsDrawingTool(uIDUse) Then
                ' it is a symbol
                
                abTool.Category = SAXRes.GetLocalString(IDS_sa2001menuprcbas_____draw)
                
            End If
            
            ' now try and get the bitmap for the tool
            On Error GoTo SymBmpError
            errFlag = False
            
            abTool.ClearPicture
            If lSubId <> -2 Then
                ' Set the picture using the resource if this is NOT a macro menu item
                abTool.SetPicture uIDUse
    #If TOOLDEBUGGING Then
                LogMessageTools "CheckAddTool - PICTURE added ID='" & uIDUse & "' fail state = " & errFlag 'DEV_STRING
    #End If
            End If
            On Error GoTo 0
            If errFlag Then
                abTool.Style = SATB_ST_Text
            End If
            
            r_Id = uIDUse
            Set r_objTool = abTool
        End If
        CheckAddTool = True
    Else
        ' just reset the caption and tooltip
#If TOOLDEBUGGING Then
        Call LogMessageTools("MenuPrc-CheckAddTool- Updating tool '" & sSubId & "' Caption - '" & abTool.Caption & "'") 'DEV_STRING
#End If
        lToolID = abTool.toolID

        p = InStr(sSubName, Chr(9))
        If p > 0 Then
          s = Mid$(sSubName, 1, p - 1)
        Else
          s = sSubName
        End If
        If (lSubId <> -2 Or abTool.Caption = SA_VB_EmptyString) And Not bPopup And sSubName <> "" Then
            ' If this is not a macro, or there is no current caption - stops macros losing their caption
            ' and it is NOT a popup - popups cannot have their caption changed
            ' and there is a caption to use
            If abTool.Caption <> sSubName Then
                abTool.Caption = sSubName
                ' we need to search all bands to see where this is and to change it there as well
                UpdateToolInBands fMainForm.ATB, sSubId, sSubName
            End If
        End If
        
        p = InStr(CleanMenuPopup(sSubName), Chr(9))
        If p > 0 Then
          s = Mid$(CleanMenuPopup(sSubName), 1, p - 1)
        Else
          s = CleanMenuPopup(sSubName)
        End If
        If lSubId <> -2 Or abTool.Caption = SA_VB_EmptyString Then
            ' If this is not a macro, or there is no current caption - stops macros losing their caption
            abTool.ToolTipText = s
        End If
        
#If TOOLDEBUGGING Then
        LogMessageTools "CheckAddTool - Enable tool " & abTool.name 'DEV_STRING
#End If
        EnableMenuTool abTool, True     ' enable the tool
                
        If 0 = (abTool.UpdateFlags And MENUTOOL_INSERTEDINMENU) Then
            ' Tool already existed in tools collection, but has not had flag set to say it has been inserted in the menu
            CheckAddTool = True ' Pretend the tool was just added - as it has never been inserted in the menu
#If TOOLDEBUGGING Then
            Call LogMessageTools("MenuPrc-CheckAddTool- Already exists, but never been inserted in the menu '" & abTool.name & "'") 'DEV_STRING
#End If
        End If
        
        r_Id = abTool.toolID
        Set r_objTool = abTool
    End If

#If TOOLDEBUGGING Then
    strLogMessageToolsPrefix = Space$(Len(strLogMessageToolsPrefix) - 1)
#End If
    Exit Function
    
SymBmpError:
    errFlag = True
    Resume Next
ToolbarError1:
    
    LogMessage "ToolbarError1 - sSubID = " & sSubId 'DEV_STRING
    
    Resume Next

End Function

Private Sub DisableToolAndAllSubTools(ATB As SAToolbar, _
                                   abTool As SAToolbarTool)
    Dim lngIndex As Long
    If abTool Is Nothing Then Exit Sub
                
    
    If IsMacroTool(abTool.toolID) Then Exit Sub ' Never remove macros everywhere, esp. from the tools collection
    
                
#If TOOLDEBUGGING Then
    LogMessageTools "DisableToolAndAllSubTools - " & abTool.name 'DEV_STRING
#End If
                
    Dim abToolSub As SAToolbarTool
    Dim abBand As SAToolbarBand
    
'''    abTool.Enabled = False  ' explicitly disable (no timer)
    EnableMenuTool abTool, False        ' flag for timer to disable
    
    abTool.Checked = False  ' and say it is not checked
    If abTool.SubBand <> SA_VB_EmptyString Then
        Set abBand = ATB.Bands(abTool.SubBand)
        For lngIndex = 0 To abBand.Tools.Count - 1
            Set abToolSub = abBand.Tools(lngIndex)
            DisableToolAndAllSubTools ATB, abToolSub
        Next
    End If
    
' TODO TOOLBAR - is this a CodeJock comment or an ActiveBar comment??
' See how we get on by not removing the tools, just disabling them
' This will be more efficient - but may cause QA confusion
'
'    ' A bug in the toolbar does not free the picture resource for the main tools
'    ' collection - although it does seem to for the tools collection in a band.
'    ATB.Tools(abTool.Name).SetPicture 0, Nothing, 0  ' and remove it from the tools collection
'    ATB.Tools.Remove abTool.Name    ' and remove it from the tools collection
End Sub

Private Function FindLastDrawingToolPos(ByRef r_objToolsCol As SAToolbarTools)
    Dim objTool As SAToolbarTool
    Dim lngPos As Long
    Dim lngIndex As Long
    Dim strName As String
    Dim strCaption As String
    Dim lngID As Long
    
    If r_objToolsCol Is Nothing Then
        Exit Function
    End If
    
    For lngIndex = 0 To r_objToolsCol.Count - 1
        Set objTool = r_objToolsCol(lngIndex)
        ' for VC..
        lngID = objTool.toolID
        strName = objTool.name
        strCaption = objTool.Caption
        
        If Not Left(objTool.name, 3) = "TB_" _
        And Not IsDrawingTool(objTool.toolID) _
        And Not objTool.IsDrawMenuPopup Then 'DEV_STRING
            Exit For
        End If
        lngPos = lngPos + 1
    Next
    FindLastDrawingToolPos = lngPos
End Function

Private Sub UpdateDrawPopupPic(ByRef r_objToolsCol As SAToolbarTools, ByVal v_lngID As Long)
    Dim objTool As SAToolbarTool
    Dim lngIndex As Long
    Dim strName As String
    Dim strCaption As String
    Dim lngID As Long
    
    If r_objToolsCol Is Nothing Then
        Exit Sub
    End If
    
    For lngIndex = 0 To r_objToolsCol.Count - 1
        Set objTool = r_objToolsCol(lngIndex)
        ' for VC..
        lngID = objTool.toolID
        strName = objTool.name
        strCaption = objTool.Caption
        
        If objTool.toolID = v_lngID Then
            If Not objTool.SubBand Is Nothing Then
                If objTool.SubBand.Tools.Count >= 1 Then
                    objTool.CopyPicture objTool.SubBand.Tools(0)
                    Exit For
                End If
            End If
        End If
    Next
End Sub

Private Sub EnsureToolboxExists()
    Dim objBand As SAToolbarBand
    
    ' do the toolbox stuff
    If Not bToolBoxExists Then
        On Error Resume Next
        Set objBand = fMainForm.ATB.Bands(sToolboxBand)
        On Error GoTo 0
        If objBand Is Nothing Then
            fMainForm.ATB.Bands.Add sToolboxBand, SATB_BT_NORMAL
        End If
        fMainForm.ATB.Bands(sToolboxBand).Visible = bDisplayToolBox
        
        ' Sort out the diagram bar
        EnableAllDrawingTools True
        bMenusChanged = True    ' flag for timer to activate

        bToolBoxExists = True
    End If
End Sub

Private Sub TrySetupStereotypeBand(ByVal sBand As String, ByVal bChecked As Boolean)
    Dim objBand As SAToolbarBand
    Dim lngPosn As Long
    Dim objTool As SAToolbarTool
    
    If LastToolAddedSubBand = SA_VB_EmptyString Then  ' No stereotype set up yet
        ''''''''''''''''''''''''''''''''''''''''''''''''''''
        ' We must construct the stereotype tool, band and add the previous tool to the collection
        If Not fMainForm.ActiveWindow Is Nothing Then
            LogMessage "Creating Draw subband active form is - " & fMainForm.ActiveWindow.Caption 'DEV_STRING
        Else
            LogMessage "Creating Draw subband active form is unknown" 'DEV_STRING
        End If
        Dim sSubBand As String
        Dim aTBTool As SAToolbarTool
        Dim aTBToolID As Long
        Dim sTool As String
        
#If TOOLDEBUGGING Then
        LogMessageTools "TrySetupStereotypeBand - " & sBand
        LogMessageTools "TrySetupStereotypeBand - Removing last added tool - " & LastToolAddedSubID 'DEV_STRING
#End If
        fMainForm.ATB.Bands(sBand).Tools.Remove LastToolAddedSubID   ' Remove the last tool added (it is the first tool in the stereotype)
        lngPosn = FindLastDrawingToolPos(fMainForm.ATB.Bands(sBand).Tools)   ' Find the last drawing tool in the band
        If fMainForm.ATB.Bands(sBand).Tools.Count <= lngPosn Then
            lngPosn = -1    ' Append - the item we removed was from the end
        End If
#If TOOLDEBUGGING Then
        LogMessageTools "TrySetupStereotypeBand - Position to insert is - " & lngPosn & " of " & fMainForm.ATB.Bands(sBand).Tools.Count 'DEV_STRING
#End If
        aTBToolID = LastToolAddedToolID ' because we are creating a subband of that
        sTool = "TB_" & Format(aTBToolID) 'DEV_STRING Make up a new band name (TB_xxxx)
        sSubBand = "TB_" & GetActiveDiagramType() & GetUserMode() & sTool
        sTool = sSubBand
        
        If Not BandInATBCollection(fMainForm.ATB.Bands, sSubBand) Then
            ' The band does not already exist in the master bands collection
#If TOOLDEBUGGING Then
        LogMessageTools "TrySetupStereotypeBand - creating subband " & sSubBand & " - id = " & DrawToolbarSubBandID 'DEV_STRING
#End If
            Set objBand = fMainForm.ATB.Bands.Add(sSubBand, SATB_BT_POPUP, DrawToolbarSubBandID, SATB_TT_BUTTONDROPDOWN) ' add the new band to the bands collection (and its supporting tool)
            objBand.IsCustomizable = False  ' Don't allow user customization of this band
        
            ' Add the tool to the subband
            Set objTool = fMainForm.ATB.Tools(LastToolAddedSubID)   ' Get the original drawing tool to add to the stereotype
    #If TOOLDEBUGGING Then
            LogMessageTools "TrySetupStereotypeBand - inserting tool " & LastToolAddedSubID & " - " & objTool.Caption & " into subband " & sSubBand & " - id = " & DrawToolbarSubBandID 'DEV_STRING
    #End If
            fMainForm.ATB.Bands(sSubBand).Tools.Insert -1, objTool  ' Insert the drawing tool in the stereotype band
            fMainForm.ATB.Bands(sSubBand).Caption = objTool.Caption
            
            dicStereoDrawTools.Add GetActiveDiagramType() & GetUserMode() & LastToolAddedSubID, aTBToolID   ' Add the stereotype to our stereotype collection
            
            ' now we can add a new tool to form the band tool (this is the tool which host the stereotype)
            If Not ToolInMasterCollection(sTool, aTBTool) Then
    #If TOOLDEBUGGING Then
                LogMessageTools "TrySetupStereotypeBand - adding tool - " & sTool 'DEV_STRING
    #End If
                Set aTBTool = fMainForm.ATB.Tools.Add(DrawToolbarSubBandID, sTool, True)
                If DrawToolbarSubBandID < DRAWTOOLBARSUBIDEND Then
                    DrawToolbarSubBandID = DrawToolbarSubBandID + 1     ' Increment the subband id for stereotype tools
                ElseIf Not bWarnedOnBreakingStereotypeBandLimit Then
                    bWarnedOnBreakingStereotypeBandLimit = True
                    SAMessageBox SAXRes.GetLocalString(IDS_sa2001menuprcbas_____toomanydropdowndrawingtoolsinthisdiagramtypensometoolswillnotbedisplayedcorrectly), vbCritical + vbOKOnly
                End If
            Else
                If CmdLineQAReporting Then
                    SAMessageBox "The stereotype top level tool already exists. This could be an error." 'DEV_STRING
                End If
            End If
            
            ' Setup the top level tool state
            aTBTool.Enabled = True
            aTBTool.Checked = bChecked
            Set aTBTool.SubBand = fMainForm.ATB.Bands(sSubBand) ' Add the subband to the top level tool
            aTBTool.Caption = objTool.Caption
            aTBTool.ToolTipText = objTool.ToolTipText
#If TOOLDEBUGGING Then
            LogMessageTools "TrySetupStereotypeBand - updating toolbar button for stereotype list " & LastToolAddedToolID & " - caption " & objTool.Caption & " - aTBTool.ToolId=" & Format(aTBTool.toolID) & " - objTool.ToolId=" & Format(objTool.toolID) 'DEV_STRING
#End If
            aTBTool.SetPicture LastToolAddedToolID      ' Set the default picture to the first tool in the stereotype group
            
#If TOOLDEBUGGING Then
            LogMessageTools "TrySetupStereotypeBand - inserting popup button " & aTBTool.name 'DEV_STRING
#End If
        End If
        
        If Not ToolInMasterCollection(sTool, aTBTool) Then
            SAMessageBox "The stereotype top level tool is missing. This could be an error." 'DEV_STRING
        End If
        
#If TOOLDEBUGGING Then
        LogMessageTools "TrySetupStereotypeBand - inserting popup button " & aTBTool.name 'DEV_STRING
#End If

        aTBTool.Visible = False                     ' Do not show it yet
        ShowMenuTool fMainForm.ATB, aTBTool, True   ' Delay showing until timer
        fMainForm.ATB.Bands(sBand).Tools.Insert lngPosn, aTBTool     ' Add the tool to the toolbox
        
        Set aTBTool = fMainForm.ATB.Bands(sBand).Tools(sTool)     ' Get the tool instance which has been put in the toolbox (not the master)
        aTBTool.ExecCommandID = LastToolAddedToolID
        
        ' Setup our 'globals' so we know what state we are in when the next tool is added to the draw menu and toolbox
        LastToolAddedSubID = sTool
        LastToolAddedToolID = aTBToolID
        LastToolAddedSubBand = sSubBand
    End If
End Sub

Private Sub TryAddDrawMenuItemToDrawSubMenu(ByVal sParentMenu As String, lSubId As Long, bChecked As Boolean, bBeginGroup As Boolean, bIsSubType As Boolean)
    Dim sSubId As String
    Dim lngPosn As Long
    Dim objBand As SAToolbarBand
    Dim objTool As SAToolbarTool
    Dim sSubBand As String
    Dim aTBTool As SAToolbarTool
    Dim aTBToolID As Long
    Dim bSpecial As Boolean
    
    sSubId = SSGetMenuID(lSubId)
    
#If TOOLDEBUGGING Then
    strLogMessageToolsPrefix = Space$(Len(strLogMessageToolsPrefix) + 1)
    LogMessageTools "TryAddDrawMenuItemToDrawSubMenu - " & sParentMenu
#End If

    With fMainForm.ATB.Bands(sParentMenu).Tools 'DEV_STRING
    
        ' The drawing tool box / menu
                    
        If dicStereoDrawTools Is Nothing Then
            Set dicStereoDrawTools = New Dictionary
            DrawToolbarSubBandID = DRAWTOOLBARSUBIDSTART    ' not really used for anything - just needs to be unique
        End If
        
        lngPosn = FindLastDrawingToolPos(fMainForm.ATB.Bands(sParentMenu).Tools)
        
        If CmdLineQAReporting Then
            If lSubId = 299 And lngPosn > 0 Then
                SAMessageBox "The drawing menu is being redrawn, but there are drawing tools already in it." & vbCrLf & "This could be an error" 'DEV_STRING
            End If
        End If
        
        If sParentMenu = BAND_DRAWLINEMENU Then
            lngPosn = fMainForm.ATB.Bands(sParentMenu).Tools.Count
        End If

#If TOOLDEBUGGING Then
        LogMessageTools "TryAddDrawMenuItemToDrawSubMenu - Last drawing tool is at Position - " & lngPosn & " of " & fMainForm.ATB.Bands(sParentMenu).Tools.Count 'DEV_STRING
#End If
        
        If bIsSubType Then
            TrySetupStereotypeBand sParentMenu, bChecked
            ''''''''''''''''''''''''''''''''''''''''''''''''''''
            ' Add the current tool to the stereotype list
#If TOOLDEBUGGING Then
            LogMessageTools "TryAddDrawMenuItemToDrawSubMenu - inserting item to subband " & LastToolAddedSubBand & " - id = " & sSubId 'DEV_STRING
#End If
            Set aTBTool = fMainForm.ATB.Tools(sSubId)
            If Not aTBTool.Style = SATB_ST_Icon Then
                ' Duplicate the icon of the first entry ONLY if no icon has been assigned to this menu item
                ' - that allows any represented definition types without depictions to have the default icon which it wouldn't get otherwise
                On Error Resume Next
                aTBTool.CopyPicture fMainForm.ATB.Bands(LastToolAddedSubBand).Tools.Item(0)
                On Error GoTo 0
            End If
            On Error Resume Next
            Set objTool = Nothing
            Set objTool = fMainForm.ATB.Bands(LastToolAddedSubBand).Tools(sSubId)
            On Error GoTo 0
            
            If objTool Is Nothing Then
                fMainForm.ATB.Bands(LastToolAddedSubBand).Tools.Insert -1, aTBTool
            End If
            aTBTool.Checked = bChecked      ' ensure that it is not checked
            aTBTool.Enabled = True          ' make it enabled
' TODO TOOLBAR - Uncomment and fix this so it remembers the last stereotype tool chosen (when the tool was not selected) when flipping diagrams
' TODO TOOLBAR - it makes tools disappear when flipping diagrams at present?? - CR20660
'            On Error Resume Next
'                Dim lActiveID As Long
'                lActiveID = fMainForm.ActiveForm.collTBSubs(LastToolAddedSubBand)
'                If lActiveID = lSubId Then
'                    Set aTBTool = fMainForm.ATB.Bands(LastToolAddedSubBand).Tools(sSubId)
'                    With fMainForm.ATB.Bands(sToolboxBand).Tools(LastToolAddedSubBand)
'                        .Caption = aTBTool.Caption
'                        .ToolTipText = aTBTool.ToolTipText
'                        .UpdateFlags = aTBTool.UpdateFlags
'                    End With
'                End If
'            On Error GoTo 0
            dicStereoDrawTools.Add GetActiveDiagramType() & GetUserMode() & sSubId, LastToolAddedToolID
            
            If LastDrawPopupAddedToolID <> 0 Then
                UpdateDrawPopupPic fMainForm.ATB.Bands(sLastDrawPopupParentBand).Tools, LastDrawPopupAddedToolID
                If Left$(sLastDrawPopupParentBand, Len(BAND_DRAWMENU)) = BAND_DRAWMENU Then
                    UpdateDrawPopupPic fMainForm.ATB.Bands(sToolboxBand).Tools, LastDrawPopupAddedToolID
                End If
                LastDrawPopupAddedToolID = 0
                objLastDrawPopupTool.ExecCommandID = LastToolAddedToolID
                Set objLastDrawPopupTool = Nothing
                sLastDrawPopupParentBand = ""
            End If
        ElseIf IsDrawingTool(lSubId) Then
            ' if it is a drawing tool - not a stereotype tool
            Set aTBTool = fMainForm.ATB.Tools(sSubId)
            aTBTool.Visible = False
            aTBTool.Checked = bChecked      ' ensure that it is not checked
            aTBTool.Enabled = True          ' make it enabled
            ShowMenuTool fMainForm.ATB, aTBTool, True    ' Delay showing of tool until timer
            
            On Error Resume Next
            Set objTool = Nothing
            Set objTool = fMainForm.ATB.Bands(sParentMenu).Tools(sSubId)
            On Error GoTo 0
            
            If objTool Is Nothing Then
                fMainForm.ATB.Bands(sParentMenu).Tools.Insert lngPosn, aTBTool
            End If
            Call SetToolSeparator(fMainForm.ATB.Bands(sParentMenu).Tools.Item(sSubId), True)
            LastToolAddedSubID = sSubId
            LastToolAddedToolID = lSubId
            LastToolAddedSubBand = SA_VB_EmptyString
            
            If LastDrawPopupAddedToolID <> 0 Then
                UpdateDrawPopupPic fMainForm.ATB.Bands(sLastDrawPopupParentBand).Tools, LastDrawPopupAddedToolID
                If Left$(sLastDrawPopupParentBand, Len(BAND_DRAWMENU)) = BAND_DRAWMENU Then
                    UpdateDrawPopupPic fMainForm.ATB.Bands(sToolboxBand).Tools, LastDrawPopupAddedToolID
                End If
                LastDrawPopupAddedToolID = 0
                objLastDrawPopupTool.ExecCommandID = LastToolAddedToolID
                Set objLastDrawPopupTool = Nothing
                sLastDrawPopupParentBand = ""
            End If
        End If
    End With
#If TOOLDEBUGGING Then
    strLogMessageToolsPrefix = Space$(Len(strLogMessageToolsPrefix) - 1)
#End If
End Sub

Public Sub EnableAllDrawingTools(ByVal bEnable As Boolean)
    Dim aTool As SAToolbarTool
    Dim lngIndex As Long
    ' TODO TOOLBAR - these enables could be done in sadesign in changegp??
    ' TODO TOOLBAR - THIS IS NOT ENOUGH!!! - we should do this in changegp with the new bHasFocus flag - but that is a LOT of EnableMenuItem lines to change right now
    
    ' Ensure all drawing tools are disabled (stops users editing menus)
    For lngIndex = 0 To fMainForm.ATB.Tools.Count - 1
        Set aTool = fMainForm.ATB.Tools(lngIndex)
        If IsDrawingTool(aTool.toolID) Then
            EnableMenuTool aTool, bEnable
        End If
    Next

    EnableMenuTool fMainForm.ATB.Tools(TOOL_ZOOMPERCENT), bEnable
    EnableMenuTool fMainForm.ATB.Tools("SAIDM_64"), bEnable  'DEV_STRING flag for enable     ' Active Zoom
    EnableMenuTool fMainForm.ATB.Tools("SAIDM_271"), bEnable  'DEV_STRING flag for enable     ' Symbol Find
    EnableMenuTool fMainForm.ATB.Tools("SAIDM_267"), bEnable   'DEV_STRING flag for enable     ' Zoom In
    EnableMenuTool fMainForm.ATB.Tools("SAIDM_268"), bEnable  'DEV_STRING flag for enable     ' Zoom Out
    
    If Not bEnable Then
        ' Only disable these 'Draw->Picture->' submenu items - they will be enabled at diagram active
        EnableMenuTool fMainForm.ATB.Tools("SAIDM_514"), bEnable  'DEV_STRING flag for disable
        EnableMenuTool fMainForm.ATB.Tools("SAIDM_220"), bEnable  'DEV_STRING flag for disable
        EnableMenuTool fMainForm.ATB.Tools("SAIDM_221"), bEnable  'DEV_STRING flag for disable
        EnableMenuTool fMainForm.ATB.Tools("SAIDM_222"), bEnable  'DEV_STRING flag for disable
        EnableMenuTool fMainForm.ATB.Tools("SAIDM_515"), bEnable  'DEV_STRING flag for disable
        EnableMenuTool fMainForm.ATB.Tools("SAIDM_97"), bEnable  'DEV_STRING flag for disable
        EnableMenuTool fMainForm.ATB.Tools("SAIDM_98"), bEnable  'DEV_STRING flag for disable
        EnableMenuTool fMainForm.ATB.Tools("SAIDM_99"), bEnable  'DEV_STRING flag for disable
    End If
    
    EnableBand bEnable, BAND_SYMBOLSTYLE
    
    EnableBand bEnable, TOOL_FILLCOLOR
    EnableBand bEnable, TOOL_FONTCOLOR
    EnableBand bEnable, TOOL_PENCOLOR
    
    EnableMenuTool fMainForm.ATB.Tools(TOOL_DRAWMENU), bEnable  'DEV_STRING flag for enable
    
    If bEnable = False Then
        EnableModes bEnable
    End If

    bMenusChanged = True    ' flag for timer to activate
End Sub

Private Sub RemoveDrawToolBox()
    If bToolBoxExists Then
        fMainForm.SSAtbUpdating = True
              
        If Not g_bCacheDrawMenus Then
            RestoreBaseDrawBand BAND_DRAWMENU
        
            KillDrawMenus
        
            Set dicStereoDrawTools = Nothing
            dicDrawPopupsByTypeModeName.RemoveAll
        
        End If
        RestoreBaseDrawBand BAND_DRAWTOOLBOX
        RestoreBaseDrawBand BAND_DRAWLINEMENU
        RestoreBaseDrawBand BAND_DRAWNODEMENU
        DrawMenu_RemoveDrawMenuTool
    
        bToolBoxExists = False
        
        bMenusChanged = True
        fMainForm.SSAtbUpdating = False
    End If
End Sub

Public Sub CreateCustomTool(uID As Long, strMenuEntry As String, strToolTip As String, pBitmap As StdPicture, Optional ByVal v_strToolIDToGetPictureFrom As String = "") 'DEV_STRING
Dim strId As String
Dim i As Long
Dim abTool As SAToolbarTool
Dim abTempTool As SAToolbarTool
Dim p As Long, s As String

    strId = SSGetMenuID(uID)

    ' remove any previous tool
    On Error Resume Next
    ShowMenuTool fMainForm.ATB, strId, False
    fMainForm.ATB.Tools.Remove strId
    On Error GoTo 0
    
    On Error GoTo ToolbarError1
    Set abTool = fMainForm.ATB.Tools.Add(uID, strId, , , False)     ' Don't set the default bitmap - this stops it adding correctly later
    'abTool.ControlType = SATB_TT_BUTTON ' no-op
    p = InStr(strMenuEntry, Chr(9))
    If p > 0 Then
      s = Mid$(strMenuEntry, 1, p - 1)
    Else
      s = strMenuEntry
    End If
    abTool.Caption = s

    If strToolTip = SA_VB_EmptyString Then strToolTip = strMenuEntry
    p = InStr(CleanMenuPopup(strToolTip), Chr(9))
    If p > 0 Then
      s = Mid$(CleanMenuPopup(strToolTip), 1, p - 1)
    Else
      s = CleanMenuPopup(strToolTip)
    End If
    abTool.ToolTipText = s
    
    abTool.Category = SAXRes.GetLocalString(IDS_sa2001menuprc_____customized)

    If v_strToolIDToGetPictureFrom <> SA_VB_EmptyString Then
        ' The picture should be used from the other tool
        On Error Resume Next
        Set abTempTool = fMainForm.ATB.Tools(v_strToolIDToGetPictureFrom)
        On Error GoTo 0
        If Not abTempTool Is Nothing Then
            ' Found the tool - get it's toolid
            abTool.SetPicture abTempTool.toolID
        Else
            ' Failed - use text
            abTool.Style = SATB_ST_Text
        End If
    Else
        ' Use the picture provided
        On Error Resume Next
        abTool.SetPicture pBitmap
        On Error GoTo 0
    End If
    Exit Sub

ToolbarError1:
    LogMessage "Error creating custom tool - CreateCustomTool1 - uID = " & uID 'DEV_STRING
    Resume Next

End Sub

Public Sub RemoveCustomizedTools()
    Dim abTool As SAToolbarTool
    Dim lngIndex As Long

    ' remove any previous tool
    For lngIndex = fMainForm.ATB.Tools.Count - 1 To 0 Step -1
        Set abTool = fMainForm.ATB.Tools(lngIndex)
        If abTool.Category = SAXRes.GetLocalString(IDS_sa2001menuprc_____customized) Then
            fMainForm.ATB.Tools.Remove abTool.name
        End If
    Next
End Sub

Public Sub UnHideAndEnableAllTools(ByVal hWnd As Long)
    Dim abTool As SAToolbarTool
    Dim lngIndex As Long
    '' TODO DECOUPLE - don't know why this is done??
        '' TODO DECOUPLE - no longer used!!!

    LockWindowUpdate hWnd
    
    For lngIndex = 0 To fMainForm.ATB.Tools.Count - 1
        Set abTool = fMainForm.ATB.Tools(lngIndex)
        abTool.Visible = True
        abTool.Enabled = True
    Next
    
    LockWindowUpdate 0
End Sub

Public Function Do_Insert_Menu_Proc2(ByVal hMenu As Long, _
                                 ByVal uPosition As Long, _
                                 ByVal uFlags As Long, _
                                 ByVal uIDNewItem As Long, _
                                 ByVal lpszNewItem As Long _
                                 ) As Long
' Used by the menu test mode
End Function

Public Function Do_Append_Menu_Proc2(ByVal hMenu As Long, _
                                 ByVal uFlags As Long, _
                                 ByVal uIDNewItem As Long, _
                                 ByVal lpszNewItem As Long _
                                 ) As Long
' Used by the menu test mode
End Function

Public Function Do_Delete_Menu_Proc2(ByVal hMenu As Long, _
                                 ByVal uPosition As Long, _
                                 ByVal uFlags As Long _
                                 ) As Long
' Used by the menu test mode
End Function

Public Function Do_Remove_Menu_Proc2(ByVal hMenu As Long, _
                                 ByVal uPosition As Long, _
                                 ByVal uFlags As Long _
                                 ) As Long
' Used by the menu test mode
End Function

Public Function ShowContextMenu(ByVal v_strPopupName As String, ByVal v_lngX As Long, ByVal v_lngY As Long, ByVal lngFlags As Long) As Long
    bInContextMenuPopup = True
    If IsContextMenu(v_strPopupName) Then
        ' Force a menu update
        bMenusChanged = True
        RedrawMenu
        
        ' The menus should be upto date now - do the popup
        ShowContextMenu = CLng(fMainForm.ATB.ShowBandAsPopup(v_strPopupName))
    End If
    bInContextMenuPopup = False
End Function

Public Sub ResetDrawToolbarOnATBLoad()
    RemoveDrawToolBox
End Sub

Public Sub EnableModesIfNeeded()
End Sub

Public Sub ApplyUserMode(minorTypeNumber As Integer, Default As String)
End Sub

Public Function GetUserMode() As String
End Function

Public Function GetActiveDiagramType() As Long
End Function

Public Sub EnableOSLCToolbar(enable As Boolean, clearlist As Boolean)
End Sub
Private Sub EnableModes(enable As Boolean)
End Sub

Private Sub DrawMenu_SetupDrawMenuTool(ByVal v_lngType As Long, ByVal v_strMode As String)
End Sub

Private Sub DrawMenu_RemoveDrawMenuTool()
End Sub

Public Function DrawMenu_RestoreForType(ByVal v_lngType As Long, ByVal v_strMode As String, ByRef r_hMenu As Long, ByRef r_lpstrXML As Long) As Boolean
End Function

Public Function DrawMenu_StoreForType(ByVal v_lngType As Long, ByVal v_strMode As String, ByVal v_hMenu As Long, ByVal v_lpstrXml As Long) As Boolean
End Function

Public Sub StoreBaseDrawBand(ByVal v_strBandName As String)
End Sub

Public Sub RestoreBaseDrawBand(ByVal v_strBandName As String)
End Sub

Sub KillStereoDrawTools(dicStereoDrawTools As Dictionary)
End Sub

Sub KillDrawMenus()
End Sub
