The title of this post says it all. Function to close window(s) run a script or series of commands and the reopen window

This function will allow button on a form to invoke a operation that requires exclusive access to the tables the form is based on, a good example is packing the table the form is based on. It can also be used anywhere exclusive access is required to all tables such as a backup or restore operation. In fact the code is based on the backup code generated by the xBasic Genie (I think?) However the code has been extensively commented so it should be easier to figure out how it works.

Code:
'Date Created: 06-Feb-2013 11:57:47 AM
'Last Updated: 14-Mar-2014 10:29:57 PM
'Created By  : Paul Verboom
'Updated By  : Paul Verboom
FUNCTION zCloseWinRun AS C (Code as C, Script as C, WindowName as C, WindowClose as L, CloseOther as L, Message as L)
'---------------
'zCloseWinRun
'---------------
'This function optional closes all windows (forms and browses)
'Optionally including the form or browse it was launch from.
'The main menu is not closed.
'Optionally it will then play the script specified as a parameter.
'or optionally execute a series of commands provided
'Finally if it was closed it will reopen the form or browse
'it was lunched from if

'The form or browse it was played from can be specified as paramter.
'If left blank function will determine what form it was called from.

'Normally it is not possible for a script launched from a 
'form or browse to close that form or browse while it is
'still running. The proper command can be executed but,
'the window will not close till the script which is 
'child of the form or browse is completed.
'Sometimes a script needs exclusive access to a table that
'is displayed by the underlying form. This is what this
'script is for

'The calling script must end after calling this function.
'The script that calls this function can be called from a form or browse.
'This function can be used in the button OnPush Event to
'launch the script in question.

'Calling Parameters
'
'Code            - Code to execute after closeing window and before calling script
'Script            - Script to call after closing window that called this function
'WindowName        - Name of window that called this function
'                    If null will be determined by function
'                    Must be specified if function is not directly called by script run from the form
'WindowClose    - if .T. close the window that called this function
'CloseOther        - if .T. close all other windows except mainmenu, & control panel
'Message        - if .T. display message to user that explains what is about to happen
    

    '-----------------
    '// Variables ----
    '-----------------
    dim open_windows as c         'List of open windows on system
    dim current_window as c     'Current window that ran this cript
    DIM varP_Window as p        'pointer to window about to be close
    
    dim topparent_name as c     'used to close top parent
    dim cmd as c 
    dim condition as c 
    dim open_sessions as c 
    dim open_session_count as n 
    
    '------------------------------------------------------
    '// Attempt to determine Window Name if not provided --
    '------------------------------------------------------
    if isnull(WindowName) .AND. WindowClose 
        if is_object(topparent.this) then 
            if topparent.class() = "form" .OR. topparent.class() = "browse" then 
                WindowName = topparent.name()
            else
                ui_msg_box("Internal Error","CloseAllWindowRun was not called from a form or browse")
            end if
        else
            ui_msg_box("Internal Error","CloseAllWindowRun was not called from a form or browse")
        end if        
    end if

    '-----------------------------------------------------------------------
    '// Tell the user what is about to happen give them a change to abort --
    '-----------------------------------------------------------------------
    if Message
        text = <<%text%
        You have selected an operation that requires exclusive access to all/some tables.
        
        If you are using eSum on multiple workstations this operation may fail if other users have the required tables open.
        
        If you proceeed all open windows will be closed. All edits in progress will be saved. No data will be lost!
        
        More information on the selected operation will be given after this screen.
        
        The window you selected the operation from will close if you proceed but it will be reopened at the end of the operation.
        %text%
        
        Dialog = <<%dlg%
        {region}
        {text=55,17:text};
        {endregion};
        {line=1,0};
        {region}
             <*15&Proceed!Proceed>         <15&Cancel!CANCEL>
        {endregion};
        %dlg%
        
        Result = ui_dlg_box("eSum",Dialog)
        if Result <>"Proceed" then
            end
        end if    
    end if
    
    '-------------------------
    '// Close other Windows --
    '-------------------------
    if CloseOther
        'get list of open windows
        open_windows = a5_list_open_windows()    
        'remove current browse or form from this list
        'it is a special situation and will be treated differnently below
        open_windows = word_subtract(open_windows,WindowName,crlf())  
        'remove menu from list
        open_windows = word_subtract(open_windows,"menu",crlf())
        'remove control panel from list
        open_windows = word_subtract(open_windows,"ControlPanel",crlf())
        
        'Close each window but check for pending changes
        for each Window in open_windows    
        
            'If the window name was specified without a leading ":", then add it.
            if left(alltrim(Window),1) <> ":" then 
                Window = ":"+alltrim(Window)
            end if
            
            'Get a pointer to the specified window
            varP_Window = obj(Window)
        
            'The window does exist, so close it
            'Check to see that the object supports the "mode_get()" method
            if varP_Window.has_method("mode_get") then 
                'Save any unsaved data before closing the window
                DIM mode as c
                mode = varP_Window.mode_get()
                if (mode = "ENTER" .or. mode = "CHANGE")  then
                    varP_Window.commit()
                    'Check to see if the record was successfully saved
                    if varP_Window.mode_get()<>"VIEW" then
                        error_generate("Unable to save your changes Please correct and save, or discard your changes")
                        end
                    end if
                end if
            end if 
            'Close the window
            varP_window.close(.f.)
        next
    end if
        
    '-------------------------------------------------------
    '// Optionally Launch Script and Close calling Window --
    '-------------------------------------------------------
    'If we need to close close the window that called this script 
    '(parent window) and then run a script it cannot be done directly
    'from this script. Although a command to close the parent window
    'can be executed in this script the window will not close until
    'functions and scripts that are a child of this parent finish.
    'It which point the script having completed cannot run the required
    'script. 
    'If we need to close the parent window and run a script a trick
    'needs to be used. A series of commands is set to be triggered
    'when the session number drops by one. The session number will drop
    'when the parent window is closed. The parent window will be closed by 
    'this script, but the command to run and the reopening of the parent 
    'window will be in the series of triggered commands.
    
    'This function can close the Parent Window or Run a script without 
    'using this trick but not both 
    'the trick must be used to execute code
    
    '-----------------------
    '// Just run a script --
    '-----------------------
    IF (.NOT. isnull(Script)) .AND. (.NOT. WindowClose) .AND. (isnull(Code))
        script_play(Script)
        
    '----------------------------------------------------
    '// Close Parent Window and run Script and/or Code --
    '----------------------------------------------------
    ELSEIF ((.NOT. isnull(Script)).OR. (.NOT. isnull(Code))) .AND. WindowClose
                
        
        'Command to run before we reopen the window
        If .NOT. isnull(Code) then
            cmd = cmd + crlf() + Code + crlf()
        end if

        'Script to run before we reopen the window
        If .NOT. isnull(Script) then
            cmd = cmd + crlf() + "script_play(" + quote(Script) + ")" + crlf()
        end if
    
        'sessions are used by expression that triggers are commands
        'when this script finally finishes the session count will drop
        open_sessions = session_enum()
        open_session_count = line_count(open_sessions)
    
        'The command needed to reopen the form or browse 
        if topparent.class() = "form" then 
            cmd = cmd + "dim tempP as p; tempP = form.view(" + quote(topparent.name(1)+"@" + topparent.Dictionary_Get(1))+")"
        else
            cmd = cmd + "dim tempP as p; tempP = browse.view(" +quote( topparent.name(1)+"@" + topparent.Dictionary_Get(1))+")"
        end if 
        
        if a5_IsMaximized() = .t. then 
            cmd =  cmd +  crlf() +"xbasic_wait_for_idle()" + crlf() +  "tempP.maximize()" + crlf()
        end if 
        
        'set up trigger that operates the commmands
        'when the number of sessions is one less than the number we currently
        'have when this script and the calling form or browse have closed
        condition = "line_count(session_enum()) =  " + (open_session_count - 1 )
        
        'is the control panel hidden? 
        'if so then you have to temporarily show it, or else the database will close
        'after you close this form.
        'Not needed where we leave Main Menu open but left
        'it in anyway doesn't hurt.
        if ControlPanel.IsVisible() = .f. then 
            ControlPanel.Minimize()
            cmd = cmd + crlf() + "controlpanel.hide()"
            if a5_IsMaximized() then 
                topparent.restore()
            end if 
        end if 
    
        '! Debug stuff
        '!trace.WriteLn("Commands to run when session ends")
        '!trace.WriteLn(cmd)
        '!trace.WriteLn("")
    
        'now set commands that will run once all this is done
        on_condition(condition,cmd)
    end if
    
    '-------------------------------
    '// Close the parent Window ----
    '-------------------------------
    IF WindowClose
        varP_Window = obj(WindowName)
    
        'The window does exist, so close it
        'Check to see that the object supports the "mode_get()" method
        if varP_Window.has_method("mode_get") then 
            'Save any unsaved data before closing the window
            DIM mode as c
            mode = varP_Window.mode_get()
            if (mode = "ENTER" .or. mode = "CHANGE")  then
                varP_Window.commit()
                'Check to see if the record was successfully saved
                if varP_Window.mode_get()<>"VIEW" then
                    error_generate("Unable to save your changes Please correct and save, or discard your changes")
                    end
                end if
            end if
        end if 
        'Close the window
        varP_window.close(.f.)
    end if
    
END FUNCTION