rem
rem    Freeform303
rem    Copyright 1995 to 2003 Shoptalk Systems
rem    All rights reserved.
rem    This program is an open source, community project and may not be
rem    sold as a commercial product.  Do not remove this copyright notice.
rem
rem    This program lets you graphically lay out windows and their controls,
rem    and then converts this visual layout to Liberty BASIC source code
rem    that you can paste into your Liberty BASIC programming session.
rem    Modified for use with Windows 95/98/ME/2K/XP.
rem    Only for use with Liberty BASIC 3.0 or higher.
'----------------------------------------------------------------------
'
'This release is named Freeform303.  It is based on the Freeform3_032703
'release.  Only the places where the lbasic302.ini file is named are
'changed from that release to lbasic303.ini.
'
'Released March 27,2003  Freeform3_032703
'Updates by John Davidson
'e-mail address: johnshomeport@yahoo.com
'home page:      http://www.geocities.com/johnshomeport/

'   • Allow user to import code to any branching control.
'   • Now displays current form in the main GUI titlebar.
'   • Output code start and quit branches are now related to current GUI.
'   • [Setup] [quit] are now based on the GUI handle.
'     For #main - [setup.main.Window][quit.main]
'   • Now remembers last path for forms and bmps
'   • Code by Dennis McKinney, The Liberty Belle:
'     http://libertybelle.0catch.com/
'     This code prevents tooltip,output code, from running under XP.
'
'Released December 31,2003  Freeform3_123102
'Updates by John Davidson
'e-mail address: johnshomeport@yahoo.com
'home page:      http://www.geocities.com/johnshomeport/
'
'   • No longer opens the 'name' dialog when
'       inspect each control when created' has been selected.
'
'   • Added some user selected default settings.
'   • Fixed buttons on dialog type window workspace.
'   • Changed form save extension to ffa futures can be ffb, ffc, etc
'       add a bunch of blank lines to ini and ffa for future use.
'   • fixed code so statusbar code is not created for a _nf type gui
'   • Added fonts for controls.
'
'Released November 2,2002  Freeform3_110102  Test Release
'Updates by John Davidson
'e-mail address: johnshomeport@yahoo.com
'home page:      http://www.geocities.com/johnshomeport/
'   • Now adds fonts to all controls, in output code, for graphic type
'       windows.
'   • Adjusted grid
'   • A popup listbox that contains all controls and their perimeters,
'       this will allow you to edit controls that are initialized
'       "off screen".
'   • Added a "selectall" routine for all textboxs,in dialogs used by
'       Freeform, pretty cool huh?
'       This routine was taught to me by SirCodesAlot and Bill Jennings.
'       This feature will cary over to any new textbox, with no code change,
'       added in the future.
'   • Fixed redraw when another application has covered the form.
'   • Control location for selected control displayed in freeform.
'   • Now selecting a color for a control sets the default color for that
'       type of control to the selected color.
'   • RGB Colors now accepted for graphics windows and graphicboxs
'   • Added "Run" button to Freeform.
'       ----BE SURE TO INCLUDE THE NEW BMP's WITH RELEASE
'     button26.bmp
'   • Now removes the 'Edit' menu when the last texteditor is removed.
'   • Added active position and size display for controls and GUI.
'   • Combined 'Infobox' and 'Window Properties' dialogs.
'   • Added error trapping for maximum number of controls.
'   • Fixed routine to replace a bmp button.
'Released September 24,2002  Freeform3_0830c  Test Release
'Updates by John Davidson
'   • FINALLY fixed a bug in the menu editor that was causing the menus to
'       foul when a menu, with no items, was moved.
'       Because this bug has been in FF for a long time and, to my knowledge,
'       has never been reported, this fix was just for me!!!
'   • Freeform now adds only one instance of a branch label to the output
'       code.
'       This allows more than one control may access common branches and
'       allows you to add a button or, other control, to specify "[quit"]
'       to exit your program.
'   • Added routine to fix branch labels when adding new controls
'       and require branch labels for buttons and bmpbuttons.
'       This also allows radiobuttons and checkboxs to use null branches.
'   • Freeform 3 no longer adds "TempFile.bas" to LB's mru.
'   • Made an attempt to keep Groupboxs and comboboxs in back of other
'       controls.
'       This is  definitely not perfect and will be need to addressed in
'       the future.
'   • Changed code in several of the dialogs to prevent redrawing GUI
'       unnecessarily.
'       This caused the GUI to "flash" when a dialog was canceled.
'   • Fixed a "fill" to eliminate some of the "buttonface flash" when
'       redrawing the GUI.
'   • Turned on the "hot keys"
'       Note:
'       Hotkeys do not work when "info window" has focus.
'   • Added a couple of checkboxs in the menu routines to allow multiple entries.
'       These were added for testing purposes and I just left them in.
'   • Cleaned up the menu output code, added continuation characters.
'   • Removed the notices when repairing branch labels to improve form development flow.
'   • Fixed grid redraw that was not redrawing over completely the gui
'   • Removed popmenu selection "Color" because this only used to control
'       the default color.
'   • Fixed font in "Window" menu, "Font for control" selection.
'       They were not sized properly.
'   • fixed broken flush statements keeping Freeform from redrawing itself
'       after another app has covered it and freeform's was clicked.
'Released August 28,2002
'Updates by John Davidson
'   • For those who don't like working in a full screen, clicking
'       Freeform's maximize/restore button will now "restore" Freeform
'       to fit the default form size.
'   • Window position now defaults to center.
'   • Cleaned up the output code that was causing an
'       unnecessary number of TextboxColor$ and the like to appear in the
'       code.
'       The original code is by David Drake.
'   • Fixed the exit routine where you would be prompted to save before
'       exiting even though the form had just been saved.
'   • Added a "Save as" routine and eliminated the prompt when saving a
'       previously saved form.
'   • Now automatically adds the default extension if is missing.
'   • Changed the two button confirm dialog, used to query for "save file"
'       to a three button yes/no/cancel.
'   • Cleaned up the output code for tool tips using
'       Dennis McKinney's EZ ToolTips, available at The Liberty Belle:
'       http://libertybelle.0catch.com/ and TOOLTIPS32.BAS By
'       Brent D. Thorn, as examples.
'       The original tooltip code by David Drake and Alyce Watson.
'   • Cleaned up the statusbar output code.
'Released August 23,2002
'Updates by John Davidson
'   • Changed popups to dialog_modal or always on top.
'   • Fixed some of the API wrappers that were still in 16 bit format.
'   • Fixed font in Properties window.
'   • Fixed some of the flushes that were not flushing.
'   • Fixed menu module:
'       Some places the menu variables were being initialized with 0
'       and other places were initialized with 1.
'   • Fixed problem with statusbar not clearing when New was selected.
'   • Added "Wait" statements for menu items in output code.
'   • Added code to create statusbars in graphics type windows.
'   • Maybe someone could add the resize code.
'Released August 24,2002
'Updates by John Davidson
'   • Prompt for save when save is already performed
'   • Add a tooltip toggle option.
'       When the tooltip menu item checked the output code for the tooltips
'       will not be produced.
'       If you have entered tooltip text and opt to not produce the tooltip
'       code, the tooltip info you entered is not erased and can be output
'       if you uncheck the "Do Not Produce Tool Tips" menu option.
'--------------------------------
'--------------------------------
    'Freeform 3 update 04/20/2002
    'Notes on latest release:
    '***********
    '* Added:- *
    '***********  (Newest at top)

    '->Added a resize handle at the middle right & middle bottom of objects
    '->Because of user requests, an new dialog for menus with
    '  Add/Delete/Edit/Up/Down buttons for Menu & the Menu Items - Stephen Rose
    '->an option for a menu seperator when adding/editing menu Items
    '->a help file!  Thanks, Alyce
    '->a window properties dialog - Double-click on window to open
    '->the ability to change individual box colors
    '   (doesn't have to be global - Thanks, Cameron)
    '->now allows one to save an empty window
    '->an Infobox that stays on top and dynamically updates
    '->Modified statusbar code to take into account differences between window types
    '->Up-to-date toolbar in new location
    '->Graphics resemble Win95/98/ME layout and 3D-look
    '->HELP menu present, but no help exists yet
    '->the ability to double-click on menu and open "Edit menu" dialogue
    '->the ability to give controls tooltips
    '->the ability to add statusbar
    '->the ability to center gui
    '->the window types window_popup and dialog_popup
    '->the color option "buttonface"
    '->ForegroundColor and BackgroundColor options
    '->ctrl-key menu shortcuts
    '->Ctrl+C element copying
    '->Right-click popups they are context-sensitive (select control first!)
    '->Places option in Settings menu to make tooltips "always on"
    '->Includes bitmap size with bitmap buttons
    '->a reminder to the user that LB adds an EDIT menu when a TEXTEDITOR control is included
    '->a trapclose feature to outline mode so that code can be tested without errors
    '->the ability to choose UpperLeftX and UpperLeftY for window
    '->the ability to type in window size, if desired
    '->the ability to specify colors for Combobox, Listbox, Textbox and Texteditor and
    ' reflects those changes in the Freeform display
    '->the ability to place visible snap grid on form
    '->the ability for FF to now save all color attributes to the file.
    '->When choosing a new form, all colors reset to default
    '->Groupboxes now look on screen as they in the generated window
    '->the ability to execute form code straight from Freeform and see whether form works
    '->the ability to specify default bitmap path in Settings menu
    '->a trap that displays graphic-type windows without background and foreground color support

    '***********
    '* Fixed:- *
    '*********** (Newest at top)

    '->Menu fixes:-
    ' -Now you can now delete the edit menu if you have a texteditor..
    ' -Fixed drawing of hotkeys on menu,Before one letter menus were hotkeys
    ' -Fixed position of menu list
    '->Changing a Bmpbutton picture would give the object the long
    'filename as the object name and would crash when loading it if you had
    'Spaces
    '->bugs which prevented the form in Freeform from looking like form
    '->a bug in the Windows Property box that did not change the window handle
    '->a bug that messed up the width of checkbox and radiobutton controls
    '->a bug that caused all controls to be same color once one was changed
    '  now default color is WHITE
    '->a bug that prevented changing color of graphicboxes
    '->"Output --> Test Code" now works!  Thanks, Alyce.
    '->Now saves grid dialog preferences
    '->bug that caused controls to shift down when changing window type to "dialog"
    '->keyboard shortcuts  - Thanks John Davidson and Alyce Watson!
    '->bug that put wrong-colored LB icon on dialog toolbars
    '->the control ordering numbers positions
    '->the Win3.1 options -> now Eliminated
    '->the menu bar problem when window color changed
    '->Centered several dialog windows
    '->the menu coloring
    '->arrow button control placement
    '->Redesigned menu to reflect new functions
    '->the bug that produced faulty code for filling graphicboxes
    '->the bug that produced odd-looking object names in copied controls
    '->When choosing a new form, all colors reset to default

    'Special thanks to those who contributed code:
    '   Alyce Watson
    '   John Magne Spilling
    '   Stephen Rose

    'Special thanks to those who found bugs:
    '
    '    Cameron Arnott
    '   Jay Shrimplin
'****************************************
    ffVersion$ ="03-27-03"    '        **
'               "Freeform3_dd/mm/yy    **
'****************************************
    title$="Freeform3 "+ffVersion$+" for Liberty BASIC"
    openTemplate$= "*.ffa;*.fr3"
    saveTemplate$="*.ffa"
    for x=1 to len(ffVersion$)
     if mid$(ffVersion$,x,1)<>"-" then ini$=ini$+mid$(ffVersion$,x,1)
    next x
    ffIni$=ini$+".ini"
    WindowWidth=562
    WindowHeight= 523
    UpperLeftX=int((DisplayWidth-WindowWidth)/2)
    UpperLeftY=int((DisplayHeight-WindowHeight)/2)
    index = 0
    resizeable$ = " combobox textbox listbox graphicbox groupbox statictext windowframe textedit button checkbox radiobutton "   'add more as you go
    newControlNumber = 0  'increment by one each time a new control is added
    qu$ = chr$(34)
    controlsThatBranch$ = " button listbox combobox bmpbutton checkbox radiobutton "
    snapOn = 1
    xInterval = 5
    yInterval = 5
    createInspect = 0

    defaultWinHandle$="#main"
    defaultWindowType$="window"
    dFont$="ms_sans_serif 10"
    windowType$=defaultWindowType$ 
    winHandle$=defaultWinHandle$
    font$(1)=dFont$
    promptOnExit=1

    gosub [defineVariables]
    windowUpperLeftX = 0
    windowUpperLeftY = 0
    windowCenterOnScreen = 1
    dim winType$(20)
    dim colorType$(20)
    dim controlFont$(100)

    winType$(0) = "window"
    winType$(1) = "window_nf"
    winType$(2) = "window_popup"
    winType$(3) = "dialog"
    winType$(4) = "dialog_nf"
    winType$(5) = "dialog_modal"
    winType$(6) = "dialog_nf_modal"
    winType$(7) = "dialog_popup"
    winType$(8) = "graphics"
    winType$(9) = "graphics_nsb"
    winType$(10) ="graphics_nsb_nf"

    colorType$(1) = "black"
    colorType$(2) = "blue"
    colorType$(3) = "brown"
    colorType$(4) = "cyan"
    colorType$(5) = "darkblue"
    colorType$(6) = "darkcyan"
    colorType$(7) = "darkgray"
    colorType$(8) = "darkgreen"
    colorType$(9) = "darkpink"
    colorType$(10) = "darkred"
    colorType$(11) = "green"
    colorType$(12) = "lightgray"
    colorType$(13) = "palegray"
    colorType$(14) = "pink"
    colorType$(15) = "red"
    colorType$(16) = "white"
    colorType$(17) = "yellow"
    colorType$(18) = "buttonface"

    oldBgColor$    ="buttonface"
    oldFgColor$    = "black"
    oldBoxColor$   = "white"
    displayFormat = 1


    gosub [loadIniFile] ' Load initial variables from ini file
    toolTipControl=displayToolTip
    tooltipFlag= displayToolTip

[setUpWindowAndOpenIt] ' Set up window and open it
    nomainwin
    loadbmp "systemBoxDialog","bmp\95sysbxd.bmp"
    loadbmp "systemBox",      "bmp\95sysbx.bmp"
    loadbmp "minBox",         "bmp\95minbx.bmp"
    loadbmp "maxBox",         "bmp\95maxbx.bmp"
    loadbmp "maxBox2",        "bmp\95maxbx2.bmp"
    loadbmp "closebox",       "bmp\95exit.bmp"
    loadbmp "comboButton",    "bmp\cmbobttn.bmp"
    loadbmp "radioButton",    "bmp\radibttn.bmp"
    loadbmp "checkBox",       "bmp\checkbox.bmp"
    loadbmp "scrollUp",       "bmp\scrlup.bmp"
    loadbmp "scrollDown",     "bmp\scrldown.bmp"
    loadbmp "scrollRight",    "bmp\scrlrght.bmp"
    loadbmp "scrollLeft",     "bmp\scrlleft.bmp"
    loadbmp "toolbar",        "bmp\toolbar2.bmp"

    menu #form, ""
    menu #form, "&File",_
        "&New             Ctrl+N",  [newFile],_
        "&Open            Ctrl+O",  [openFile],_
        "&Save            Ctrl+S",  [saveFile],_
        "Save &As...            ",  [saveFileAs],|,_
        "&Quit             Ctrl+Q", [quit]
    menu #form, "&Control",_
        "&Properties      Ctrl+I",  [inspectControl],_
        "&List All Controls",       [displayColtrolList], |,_
        "&Copy              Insert",[copyControl],_
        "&Delete           Delete", [deleteControl],|,_
        "Move to &front",           [moveToFront],_
        "Move to &back",            [moveToBack]
    menu #form, "&Menu",_
        "&Menu Editor     Ctrl+M",  [editMenus]
    menu #form, "&Window",_
        "Window &Properties",       [openWindowProperties],|,_
        "&Add/Remove Statusbar",    [toggleStatusBar],_
        "&Do Not Produce Tool Tips",[toolTipOption]
    menu #form, "&Output",_
        "&Produce Code",            [produceCode],_
        "Produce Code+&Outline",    [produceCodeAndOutline],_
        "&Test Code",               [testCode]
    menu #form, "O&ptions",_
        "&Grid Settings",           [gridDialog],_
        "&Program Settings",        [settingsDialog]
    menu #form, "&Help",_
        "&Contents      Alt+F1",    [helpContents],_
        "&About",                   [helpAbout]

    bmpbutton #form.new,    "bmp\button01.bmp", [newFile],              UL,  10, 10
    bmpbutton #form.load,   "bmp\button02.bmp", [openFile],             UL,  41, 13
    bmpbutton #form.save,   "bmp\button03.bmp", [saveFile],             UL,  72, 13
    bmpbutton #form.cut,    "bmp\button04a.bmp",[inputLoop],            UL, 104, 11
    bmpbutton #form.copy,   "bmp\button05.bmp", [copyControl],          UL, 133, 12
    bmpbutton #form.paste,  "bmp\button06a.bmp",[inputLoop],            UL, 162, 12
    bmpbutton #form.static, "bmp\button13.bmp", [addStaticText],        UL,   9, 43
    bmpbutton #form.field,  "bmp\button14.bmp", [addField],             UL,  40, 42
    bmpbutton #form.button, "bmp\button15.bmp", [addButton],            UL,  69, 41
    bmpbutton #form.bmp,    "bmp\button16.bmp", [addBmpButton],         UL, 100, 40
    bmpbutton #form.list,   "bmp\button17.bmp", [addListBox],           UL, 132, 41
    bmpbutton #form.combo,  "bmp\button18.bmp", [addComboBox],          UL, 162, 41
    bmpbutton #form.radio,  "bmp\button19.bmp", [addRadioButton],       UL, 195, 41
    bmpbutton #form.check,  "bmp\button20.bmp", [addCheckBox],          UL, 225, 41
    bmpbutton #form.group,  "bmp\button21.bmp", [addGroupBox],          UL, 256, 41
    bmpbutton #form.edit,   "bmp\button22.bmp", [addTextEdit],          UL, 288, 41
    bmpbutton #form.graphic,"bmp\button23.bmp", [addGraphicBox],        UL, 318, 41
    bmpbutton #form.inspect,"bmp\button08.bmp", [inspectControl],       UL, 226,  9
    bmpbutton #form.delete, "bmp\button07.bmp", [deleteControl],        UL, 196, 11
    bmpbutton #form.infront,"bmp\button09.bmp", [moveToFront],          UL, 258, 12
    bmpbutton #form.inback, "bmp\button10.bmp", [moveToBack],           UL, 289, 12
    bmpbutton #form.code,   "bmp\button11.bmp", [produceCode],          UL, 321, 14
    bmpbutton #form.outline,"bmp\button12.bmp", [produceCodeAndOutline],UL, 349, 12
    bmpbutton #form.runner, "bmp\button26.bmp", [testCode],             UL,376,7
    'bmpbutton #form.rr, "bmp\gridbutton.bmp",   [addGrid],              UL,349,41
    TextboxColor$="palegray"
    textbox #form.xy,380,39,85,22
    textbox #form.wh,467,39,85,22
    open title$;" - untitled" for graphics_fs_nsb as #form
    hWnd=hwnd(#form)
    CallDLL #user32, "GetParent",hWnd as long,hParent as long
    print #form, "font ";font$(1)
    print #form.xy,"!font MS_Sans_Serif 8"
    print #form.wh,"!font MS_Sans_Serif 8"
    print #form, "down;flush"
    print #form, "trapclose [quit]"
    print #form, "setfocus;when characterInput [key.pressed]"
'Used fot textbox 'selectall' and redraw if gui it has been covered by another app.
   timer 100,[testHandle]
   toolTipControl=1
TextboxColor$="white"
[drawTheWindow] ' Draw the gui for Freeform
    gosub [renderWindow]
    gosub [addWindowFrame]
    if tooltipFlag = 1 then gosub [addTooltips]
    gosub [redrawAll]
    print #form, "down;flush"
    isModified =0
    wC=0
    if tooltipFlag = 1 then toolTipControl=1 'turn tips on
    gosub [changeMenuText]
    goto  [setForSelection]

[addWindowFrame]    'add the window frame as the first object
    objectCount = objectCount + 1
    idx = objectCount
    xOrg(idx) = 1
    yOrg(idx) = 64
    width(idx) = 550
    height(idx) = 410
    type$(idx) = "windowframe"
    return
[addButton]     'add a new button to the form
    if objectCount =101 then [controlsAreMaxed]
    text$ = "Button Caption"
    if not(createInspect) then
        prompt "Please enter text for this button"; text$
        gosub [redrawAll]
    end if
    text$ = noQuotes$(text$)
    if text$ = "" then [inputLoop]
    newControlNumber = newControlNumber + 1
    objectCount = objectCount + 1
    idx = objectCount
    label$ = text$
    print #form, "font ";font$(1) 'font$(2)
    print #form,"stringwidth? label$ width"
    call addControl "button", newControlNumber, idx, width+10, 25, text$, "UL",controlDefaultColor$
    branchLabel$(idx) = "["+names$(idx)+"Click]"
    gosub [renderButton]
    if createInspect then gosub [deselectOnly] : index = idx : gosub [selectDeselect] : goto [inspectControl]
    print #form, "setfocus;when characterInput [key.pressed]"
    wait

[changeBmpButton] ' Change bmpbutton bitmap
    changeBitmapFlag = 1
    goto [addBmpButton]

[addBmpButton]     'add a new bmpButton to the form
    if objectCount =101 then [controlsAreMaxed]
    bmp$ = ""
    if currentBmpPath$="" then currentBmpPath$=bmpPath$
    bmpTemplate$= currentBmpPath$+"*.bmp"
    filedialog "Select a bitmap for this button",bmpTemplate$, bmp$
    if bmp$ = "" then [inputLoop]
    WindowWidth=228:WindowHeight=230
    UpperLeftX = DisplayWidth/2 - 222/2
    UpperLeftY = DisplayHeight/2 - 240/2
    graphicbox #bb.g, 10,10,200,100
    groupbox #bb.gbg,"",-1,-7,222,209 '120
    groupbox #bb.gbg,"",8, 3,205,111
    button #bb.okay, "OK",[bmpbuttonOkay],UL,139,120,75,23
    button #bb.cancel "Cancel",[bmpbuttonCancel],UL,139,145,75,25
    button #bb.again "Select Again",[bmpbuttonSelect],UL,139,170,75,25
    open "Bmpbutton Preview" for dialog_modal as #bb

[displayBmpbutton] ' Display the bitmap in preview window
    print #bb.g, "cls";
    loadbmp "bmptest",bmp$
    print #bb.g, "drawbmp bmptest 0 0";
    wait

[bmpbuttonSelect] ' Select again clicked, choose new bitmap
    bmp$ = ""
    filedialog "Select a bitmap for this button", "*.bmp", bmp$
    if bmp$ = "" then [inputLoop]
    goto [displayBmpbutton]

[bmpbuttonCancel] ' Cancel clicked, don't apply bitmap
    unloadbmp "bmptest"
    close #bb
    wait

[bmpbuttonOkay] ' OK Clicked, apply bitmap to button
    currentBmpPath$= fileSpec$(bmp$,1)
    gosub [bmpSize]
    close #bb
    if changeBitmapFlag = 0 then
        newControlNumber = newControlNumber + 1
        objectCount = objectCount + 1
        idx = objectCount
        call addControl "bmpbutton", newControlNumber, idx, bmpwidth, bmpheight, "", "UL",""
        bmpCount = bmpCount+1
        bmpName$(idx) = "bmp"+str$(bmpCount)
        bmpLoadName$ = "bmp"+str$(bmpCount)
        bmpFileName$(idx) = bmp$
        loadbmp bmpLoadName$, bmp$
        branchLabel$(idx) = "["+names$(idx)+"Click]"
    else
        bmpFileName$(index) = bmp$
        bmpLoadName$ = "bmp"+str$(bmpCount)
        bmpName$(index) =bmpLoadName$
        loadbmp bmpLoadName$, bmp$
        idx = index
    end if
    gosub [renderBmpButton]
    gosub [selectDeselect]

    if changeBitmapFlag = 0 then
        if createInspect then
            gosub [deselectOnly]
            index = idx
            gosub [selectDeselect]
            goto [inspectControl]
        end if
    else
        changeBitmapFlag = 0
        gosub [redrawAll]
    end if
    wait

[bmpSize]   ' Get the size of a bitmap for a button
    ' (Code courtesy Doyle Whisenant and Alyce Watson)
    open bmp$ for input as #pic
    pic$=input$(#pic,29)
    close #pic
    bmpwidth = asc(mid$(pic$,19,1)) + (asc(mid$(pic$,20,1)) * 256)
    bmpheight = asc(mid$(pic$,23,1)) + (asc(mid$(pic$,24,1)) * 256)
    return

[addField]     'add a new field (textBox) to the form
    if objectCount =101 then [controlsAreMaxed]
    newControlNumber = newControlNumber + 1
    objectCount = objectCount + 1
    idx = objectCount
    fieldDefaultColor$="white"
    call addControl "textbox", newControlNumber, idx, 100, 25, "", "",fieldDefaultColor$
    gosub [renderTextBox]
    if createInspect then gosub [deselectOnly] : index = idx : gosub [selectDeselect] : goto [inspectControl]
    print #form, "setfocus;when characterInput [key.pressed]"
    gosub [checkPosition]
    gosub [selectDeselect]
    wait
[addTextEdit]     'add a new field (textBox) to the form
    if objectCount =101 then [controlsAreMaxed]
    newControlNumber = newControlNumber + 1
    textEditControl=textEditControl+1
    objectCount = objectCount + 1
    idx = objectCount
    texteditDefaultColor$="white"
    call addControl "textedit", newControlNumber, idx, 100, 100, "", "",texteditDefaultColor$
    gosub [renderTextEdit]
    for x = 1 to menuCount
        if instr(menu$(x),"Edit") <> 0 then
            if menuItemCount(x)=0 then editMenuFlag = 1
        end if
    next x
    if editMenuFlag = 0 then
        result$ = "Edit"
        menuCount = menuCount + 1
        menu$(menuCount) = result$
        notice "Notice!"+chr$(13)+_
            "Freeform has added an EDIT menu because"+chr$(13)+_
            "LB automatically adds one to your window!"
    end if
    gosub [redrawAll]
    editMenuFlag = 0
    textEditorCount=textEditorCount+1
    if createInspect then gosub [deselectOnly] : index = idx : gosub [selectDeselect] : goto [inspectControl]
    print #form, "setfocus;when characterInput [key.pressed]"
    wait

[addComboBox]     'add a new combobox to the form
    if objectCount =101 then [controlsAreMaxed]
    newControlNumber = newControlNumber + 1
    objectCount = objectCount + 1
    idx = objectCount
    comboboxDefaultColor$="white"
    call addControl "combobox", newControlNumber, idx, 100, 100, "", "",comboboxDefaultColor$
    branchLabel$(idx) = "["+names$(idx)+"DoubleClick]"
    arrayName$(idx) = "array$("
    gosub [renderComboBox]
    if createInspect then gosub [deselectOnly] : index = idx : gosub [selectDeselect] : goto [inspectControl]
    print #form, "setfocus;when characterInput [key.pressed]"
    wait

[addListBox]     'add a new listbox to the form
    if objectCount =101 then [controlsAreMaxed]
    newControlNumber = newControlNumber + 1
    objectCount = objectCount + 1
    idx = objectCount
    listboxDefaultColor$="white"
    call addControl "listbox", newControlNumber, idx, 100, 100, "", "",listboxDefaultColor$
    branchLabel$(idx) = "["+names$(idx)+"DoubleClick]"
    arrayName$(idx) = "array$("
    gosub [renderListBox]
    if createInspect then gosub [deselectOnly] : index = idx : gosub [selectDeselect] : goto [inspectControl]
    print #form, "setfocus;when characterInput [key.pressed]"
    wait

[addStaticText]     'add statictext to the form
    if objectCount =101 then [controlsAreMaxed]
    text$ = "StaticText Caption"
    if not(createInspect) then
        prompt "Please enter the text you would like to add:"; text$
        gosub [redrawAll]
    end if
    text$ = noQuotes$(text$)
    if text$ = "" then [inputLoop]
    newControlNumber = newControlNumber + 1
    objectCount = objectCount + 1
    idx = objectCount
    label$ = text$
    print #form,"stringwidth? label$ width"
    call addControl "statictext", newControlNumber, idx, width, 20, text$, "",""
    gosub [renderStaticText]
    gosub [deselectOnly]
    if createInspect then  index = idx : gosub [selectDeselect] : goto [inspectControl]
    print #form, "setfocus;when characterInput [key.pressed]"
    wait

[addGroupBox]     'add groupbox to the form
    if objectCount =101 then [controlsAreMaxed]
    text$ = "GroupBox Caption"
    if not(createInspect) then
        prompt "Please enter the text this GroupBox :"; text$
        gosub [redrawAll]
    end if
    text$ = noQuotes$(text$)
    if text$ = "" then [inputLoop]
    newControlNumber = newControlNumber + 1
    objectCount = objectCount + 1
    idx = objectCount
    call addControl "groupbox", newControlNumber, idx, 100, 100, text$, "",""
    gosub [renderGroupBox]
    if createInspect then gosub [deselectOnly] : index = idx : gosub [selectDeselect] : goto [inspectControl]
    gosub[keepInBack2]
    print #form, "setfocus;when characterInput [key.pressed]"
    wait

[addGraphicBox]     'add graphicbox to the form
    if objectCount =101 then [controlsAreMaxed]
    newControlNumber = newControlNumber + 1
    objectCount = objectCount + 1
    idx = objectCount
    graphicboxDefaultColor$="white"
    call addControl "graphicbox", newControlNumber, idx, 100, 100, "", "",graphicboxDefaultColor$
    gosub [renderGraphicBox]
    if createInspect then gosub [deselectOnly] : index = idx : gosub [selectDeselect] : goto [inspectControl]
    print #form, "setfocus;when characterInput [key.pressed]"
    wait

[addRadioButton]     'add radiobutton to the form
    if objectCount =101 then [controlsAreMaxed]
    text$ = "RadioButton Caption"
    if not(createInspect) then
        prompt "Please enter a label for the radiobutton:"; text$
        gosub [redrawAll]
    end if
    text$ = noQuotes$(text$)
    if text$ = "" then [inputLoop]
    newControlNumber = newControlNumber + 1
    objectCount = objectCount + 1
    idx = objectCount
    label$ = text$
    print #form,"stringwidth? label$ width"
    call addControl "radiobutton", newControlNumber, idx, width+25, 25, text$, "",""
    branchLabel$(idx) = "["+names$(idx)+"Set] ["+names$(idx)+"Reset]"
    gosub [renderRadioButton]
    if createInspect then gosub [deselectOnly] : index = idx : gosub [selectDeselect] : goto [inspectControl]
    print #form, "setfocus;when characterInput [key.pressed]"
    wait

[addCheckBox]     'add checkbox to the form
    if objectCount =101 then [controlsAreMaxed]
    text$ = "CheckBox Caption"
    if not(createInspect) then
        prompt "Please enter a label for the checkbox"; text$
        gosub [redrawAll]
    end if
    text$ = noQuotes$(text$)
    if text$ = "" then [inputLoop]
    newControlNumber = newControlNumber + 1
    objectCount = objectCount + 1
    idx = objectCount
    label$ = text$
    print #form,"stringwidth? label$ width"
    call addControl "checkbox", newControlNumber, idx, width+25, 25, text$, "",""
    branchLabel$(idx) = "["+names$(idx)+"Set] ["+names$(idx)+"Reset]"
    gosub [renderCheckBox]
    if createInspect then gosub [deselectOnly] : index = idx : gosub [selectDeselect] : goto [inspectControl]
    print #form, "setfocus;when characterInput [key.pressed]"
    wait

[toggleStatusBar] ' Toggle the statusbar on and off
    if statusToggle=1 then statusToggle=0 else statusToggle=1
    if instr(windowType$,"window",0) = 0 then
        if instr(windowType$,"dialog",0) > 0 or _
           instr(windowType$,"graphics",0) > 0  then
            erMsg$="Dialog type"
            if instr(windowType$,"graphics",0) > 0  then  erMsg$="Graphics type"
            if statusToggle=1 then
             notice "Statusbars may be added to ";erMsg$;" GUIs but cannot be resized!"
            end if
        end if
    end if

    if makeStatusbar = 1 then makeStatusbar = 0 else makeStatusbar = 1
    gosub [redrawAll]
    wait

[inputLoop] ' Main interaction loop
    print #form, "when characterInput [key.pressed]"
    wait

'------ hot and function keys -------
[key.pressed] ' Handle keypresses - Thanks, Alyce!
    key$ = Inkey$
    fKeyPress=0
    CallDLL #user32,"GetAsyncKeyState",_VK_INSERT as long,fKeyPress as long
    if fKeyPress <0 then [copyControl] ' Insert key  Copy selected control
    CallDLL #user32,"GetAsyncKeyState",_VK_UP as long,fKeyPress as long
    if fKeyPress <0 then [moveUp]
    CallDLL #user32,"GetAsyncKeyState",_VK_DOWN as long,fKeyPress as long
    if fKeyPress <0 then [moveDown]
    CallDLL #user32,"GetAsyncKeyState",_VK_LEFT as long,fKeyPress as long
    if fKeyPress <0 then  [moveLeft]
    CallDLL #user32,"GetAsyncKeyState",_VK_RIGHT as long,fKeyPress as long
    if fKeyPress <0 then [moveRight]
    CallDLL #user32,"GetAsyncKeyState",_VK_F1 as long,fKeyPress as long
    if fKeyPress <0 then [helpContents]
    CallDLL #user32,"GetAsyncKeyState",_VK_DELETE as long,fKeyPress as long
    if fKeyPress <0 then [deleteControl] ' Delete key, deletes a control
    CallDLL #user32,"GetAsyncKeyState",_VK_TAB as long,fKeyPress as long
    if fKeyPress <0 then [tabControl] ' Delete key, deletes a control

'to calculate key$ subtract 64 from ascii value of the uppercase letter.
' ie: to use "A" for a hotkey  get its ascii value using
'     hKey=asc("A")
'     ascii A=65 so hKey=65
'     hKey-64=1    key$=1
   ' if asc(key$) =  3 then [copyControl]     ' Ctrl+C
    if asc(key$) =  9 then [inspectControl]  ' Ctrl+I
    if asc(key$) = 13 then [editMenus]       ' Ctrl+M
    if asc(key$) = 14 then [newFile]         ' Ctrl+N
    if asc(key$) = 15 then [openFile]        ' Ctrl+O
    if asc(key$) = 17 then [quit]            ' Ctrl+Q
    if asc(key$) = 19 then [saveFile]        ' Ctrl+S
wait
[tabControl]
    gosub [determineControl]
    if index<2 then index=1
    index=index+1
    goto [selectControl]
wait

[renderWindow] 'render the window depending on the value of windowType$
    xOrg = windowXOrigin
    yOrg = windowYOrigin
    xExt = windowXExtent
    yExt = windowYExtent
    print #form, "cls;fill  255  250  230"
    gosub [renderToolbox]
    'render gui:
    print #form, "font ";font$(1);
    print #form, "color buttonface ; down ; size 1";
    print #form, "place "; xOrg + 4; " "; yOrg + 4;
    print #form, "backcolor "; wincolor$;"";
    print #form, "boxfilled "; xOrg + xExt - 4; " "; yOrg + yExt - 4;
    if instr(windowType$, "_popup") > 0 then [noResizingFrame]
'
    'draw resizing frame
    print #form, "color buttonface ; size 1";
    if windowType$ = "dialog" then print #form, "color buttonface";
    print #form, "place "; xOrg; " "; yOrg;
    print #form, "box "; xOrg + xExt; " "; yOrg + yExt;
    print #form, "color white ; backcolor white ; size 2";
    print #form, "place "; xOrg + 1; " "; yOrg + 1;
    print #form, "box "; xOrg + xExt - 1; " "; yOrg + yExt - 1;
    print #form, "place "; xOrg; " "; yOrg;
    print #form, "color darkgray;size 2";
    print #form, "line ";xOrg+xExt-2;" ";yOrg+yExt - 2;" ";xOrg+xExt-2;" ";yOrg;
    print #form, "line ";xOrg+xExt-2;" ";yOrg+yExt - 2;" ";xOrg;" ";yOrg+yExt-2;
    print #form, "color darkgray;size 1";

[noResizingFrame] 'Jump here if window type has no resizing frame

print #form,"down;flush"
[drawTitlebar]    'draw titlebar
    if instr(windowType$,"_popup") > 0 then titlebarOffset = 0: goto [drawMenus] ' - window_popup has no tilebar
    titlebarOffset = 20
    print #form, "color black ; backcolor darkblue";
    if left$(windowType$, 6) = "dialog" then print #form, "backcolor darkgray";
    print #form, "place "; 4 + xOrg; " "; 4 + yOrg;
    print #form, "boxfilled "; xOrg + xExt - 4; " "; 4 + yOrg + 20;
    print #form, "place "; 20 + xOrg ; " "; 18 + yOrg;
    print #form, "color white; font ";font$(2)
    print #form, "\"; windowLabel$;
    print #form, "font ";font$(1)
[drawButtons]    'draw buttons
    print #form, "down"
    if instr(windowType$,"dialog") > 0 then
        print #form, "drawbmp systemBoxDialog "; xOrg + 4; " "; 4 + yOrg;
        print #form, "drawbmp closebox "; xOrg + xExt - 24; " "; 7 + yOrg;
        if instr(windowType$, "_nf") then
            print #form, "drawbmp minBox "; xOrg + xExt - 60; " "; 7 + yOrg;
            print #form, "drawbmp maxBox2 "; xOrg + xExt - 44; " "; 7 + yOrg;
        end if
    else
        print #form, "drawbmp systemBox "; xOrg + 4; " "; 4 + yOrg;
    end if
    print #form, "backcolor white ; color black ; down ; size 1";
    if windowType$ = "dialog" then print #form, "color white" ;
    print #form, "place "; xOrg + 4; " "; yOrg + 4;
    if left$(windowType$, 6) = "dialog" then [drawMenus]

    if instr(windowType$, "_nf") then
        print #form, "drawbmp minBox "; xOrg + xExt - 60; " "; 7 + yOrg;
        print #form, "drawbmp maxBox2 "; xOrg + xExt - 44; " "; 7 + yOrg;
        print #form, "drawbmp closebox "; xOrg + xExt - 24 - 1; " "; 7 + yOrg;
        goto [drawMenus]
    end if
    print #form, "drawbmp minBox "; xOrg + xExt - 60; " "; 7 + yOrg;
    print #form, "drawbmp maxBox "; xOrg + xExt - 44; " "; 7 + yOrg;
    print #form, "drawbmp closebox "; xOrg + xExt - 24; " "; 7 + yOrg;

[drawMenus] ' If present, render menus
    if menuCount = 0 then [dontDrawMenus]
    if left$(windowType$, 6) = "dialog" then menu.offset = 0: goto [dontDrawMenus]
    if instr(windowType$,"_popup") > 0 then menu.offset = 0 else menu.offset = 20 ' window_popup has no titlebar
    print #form, "backcolor buttonface;color buttonface;place ";xOrg+4;" ";yOrg+4+menu.offset;";boxfilled ";xOrg+xExt-4;" ";yOrg+25+menu.offset
    print #form, "color black ; backcolor buttonface" ;
    if Platform$ = "Windows" then print #form, "place "; 4 + xOrg; " "; menu.offset + yOrg;
    string$ = ""
    underline1$ = ""
    underline2$ = ""
    for x = 1 to menuCount '-1
    item$ = menu$(x)
    hkIndex = instr(menu$(x), "&")
    if hkIndex = 0 then [noHotKey]
    item$ = left$(item$, hkIndex - 1) + mid$(item$, hkIndex + 1)
[noHotKey]
    string$ = string$ + item$ + " "
    next x
    print #form, "place "; xOrg + 5 ; " "; menu.offset + 18 + yOrg ;
    print #form, "font ";font$(3)
    print #form, "\"; string$;
    for x = 1 to menuCount
        item$ = menu$(x)
        hkIndex = instr(menu$(x), "&")
        if hkIndex <> 0 then
            underline1$ = underline1$ + left$(item$, hkIndex - 1)
            print #form,"stringwidth? underline1$ width"
            letter$ = mid$(item$, hkIndex + 1,1)
            print #form,"stringwidth? letter$ length"
            print #form, "place "; xOrg + 5 + width; " "; yOrg + menu.offset + 21 ;
            print #form, "north ; turn 90 ; go ";str$(length)
            underline2$ = underline2$ + left$(item$, hkIndex - 1)+     mid$(item$, hkIndex + 1) + " "
            underline1$ = underline2$
        else
            underline2$ = underline2$ + item$+ " "
            underline1$ = underline2$
        end if
    next x
    print #form, "font ";font$(1)

[dontDrawMenus] ' Jump here if no menus present
    print #form, "down;flush"
    return

[renderToolbox] 'Draws toolbar on the screen
    print #form, "down;drawbmp toolbar 0 0"
    return



[renderButton] 'render the button at idx.     'type$(idx) = "button"
    'assume an font 8 bits wide
    xOrgIdx = xOrg(idx)
    yOrgIdx = yOrg(idx)+menu.offset
    label$ = label$(idx)
    print #form,"stringwidth? label$ width"
    print #form, "place "; xOrgIdx; " "; yOrgIdx ;
    print #form, "color black ; backcolor buttonface ; size 1" ;
    print #form, "down ; boxfilled "; xOrgIdx+width(idx); " "; yOrgIdx+height(idx) ;
    print #form, "size 1 ; color darkgray ; place "; xOrgIdx+2; " "; yOrgIdx+2 ;
    print #form, "box "; xOrgIdx+width(idx)-1; " "; yOrgIdx+height(idx)-1 ;
    print #form, "color white" ;
    print #form, "place  "; xOrgIdx+2; " "; yOrgIdx+height(idx)-3 ;
    print #form, "goto "; xOrgIdx+2; " "; yOrgIdx+2 ;
    print #form, "goto "; xOrgIdx+width(idx)-3; " "; yOrgIdx+2 ;
    print #form, "color black ; backcolor buttonface ; size 1" ;
    print #form, "place "; xOrgIdx+(width(idx)/2)-(width/2)+4; " "; yOrgIdx+int((height(idx)-15)/2)+12 ;
    print #form, "font ";controlFont$(idx)
    print #form, "\"; label$(idx);
    result = postRender(idx, displayOrdering,menu.offset)
    return

[renderStaticText] 'render the statictext at idx.  type$(idx) = "statictext"
    'assume an font 8 bits wide, 15 high
    print #form, "place "; xOrg(idx); " "; yOrg(idx)+15-3+menu.offset ; " ; place "; xOrg(idx); " "; yOrg(idx)+15-3+menu.offset ;
    print #form, "down ; color ";currentForegroundColor$;" ; backcolor ";currentBackgroundColor$
    print #form,"font ";controlFont$(idx)   'font$(1)
    print #form, "\"; label$(idx);
    result = postRender(idx, displayOrdering,menu.offset)
    return

[renderRadioButton] 'render the radiobutton at idx. type$(idx)="radiobutton"
    'assume an font 8 bits wide, 15 high
    label$ = label$(idx)
    print #form,"stringwidth? label$ width"
    width(idx) = width+25
    print #form, "down" ;
    print #form, "place "; xOrg(idx); " "; yOrg(idx)+menu.offset
    print #form, "drawbmp radioButton "; xOrg(idx); " "; yOrg(idx)+menu.offset;
    print #form, "color ";currentForegroundColor$;" ; backcolor ";currentBackgroundColor$;
    print #form, "place "; xOrg(idx)+16; " "; yOrg(idx)+15-3 +menu.offset;
    print #form, "font ";controlFont$(idx)
    print #form, "color ";currentForegroundColor$;";\"; label$(idx);
    result = postRender(idx, displayOrdering,menu.offset)
    return

[renderCheckBox] 'render the checkbox at idx. type$(idx) = "checkbox"
    'assume an font 8 bits wide, 15 high
    label$ = label$(idx)
    print #form,"stringwidth? label$ width"
    width(idx) = width+25
    print #form, "place "; xOrg(idx); " "; yOrg(idx) +menu.offset;
    print #form, "down" ;
    print #form, "drawbmp checkBox "; xOrg(idx); " "; yOrg(idx)+menu.offset;
    print #form, "color ";currentForegroundColor$;" ; backcolor ";currentBackgroundColor$ ;
    print #form, "place "; xOrg(idx)+16; " "; yOrg(idx)+15-3+menu.offset ;
    print #form, "font ";controlFont$(idx)
    print #form, "\"; label$(idx);
    result = postRender(idx, displayOrdering,menu.offset)
    return

[renderBmpButton] 'render the bmpbutton at idx. type$(idx) = "bmpbutton"
    'assume an font 8 bits wide
    print #form, "place "; xOrg(idx); " "; yOrg(idx) +menu.offset;
    print #form, "drawbmp "; bmpName$(idx); " "; xOrg(idx); " "; yOrg(idx)+menu.offset;
    result = postRender(idx, displayOrdering,menu.offset)
    return

[renderComboBox] 'render the comboBox at idx. type$(idx) = "combobox"
    cBoxColor$ = "white"
    if windowComboboxColor$ <> "" then cBoxColor$ = windowComboboxColor$
    if boxcolor$(idx) <> "" then cBoxColor$ = boxcolor$(idx)
    print #form, "place "; xOrg(idx); " "; yOrg(idx) +menu.offset;
    print #form, "color white ; backcolor ";cBoxColor$;"; size 1" ;
    print #form, "down ; boxfilled "; xOrg(idx)+width(idx); " "; yOrg(idx)+21+menu.offset ;
    print #form, "color buttonface ; backcolor white ; size 1" ;
    print #form, "down ; box "; xOrg(idx)+width(idx)-1; " "; yOrg(idx)+20+menu.offset ;
    print #form, "color darkgray ; backcolor white ; size 2" ;
    print #form, "down ; line "; xOrg(idx);" "; yOrg(idx)+menu.offset;" ";xOrg(idx)+width(idx); " "; yOrg(idx)+menu.offset ;
    print #form, "down ; line "; xOrg(idx);" "; yOrg(idx)+menu.offset;" ";xOrg(idx); " "; yOrg(idx)+20+menu.offset ;
    print #form, "place "; xOrg(idx)+ 3; " "; yOrg(idx) +menu.offset+ 3;
    print #form, "color ";cBoxColor$;" ; backcolor white ; size 1" ;
    print #form, "down ; box "; xOrg(idx)+width(idx)-24-3; " "; yOrg(idx)+22+menu.offset-3 ;
    print #form, "drawbmp comboButton "; xOrg(idx)+width(idx)-16 ; " "; yOrg(idx)+menu.offset+1 ;
    result = postRender(idx, displayOrdering,menu.offset)
    return

[renderTextBox] 'render the textbox at idx. type$(idx) = "textbox"
    fillIt$ = "white"
    if boxcolor$(idx) <> "" then fillIt$ = boxcolor$(idx)
    print #form, "place "; xOrg(idx); " "; yOrg(idx) +menu.offset;
    print #form, "color white ; backcolor ";fillIt$;"; size 1" ;
    print #form, "down ; boxfilled "; xOrg(idx)+width(idx); " "; yOrg(idx)+21+menu.offset ;
    print #form, "color buttonface ; backcolor white ; size 1" ;
    print #form, "down ; box "; xOrg(idx)+width(idx)-1; " "; yOrg(idx)+20+menu.offset ;
    print #form, "color darkgray ; backcolor white ; size 2" ;
    print #form, "down ; line "; xOrg(idx);" "; yOrg(idx)+menu.offset;" ";xOrg(idx)+width(idx); " "; yOrg(idx)+menu.offset ;
    print #form, "down ; line "; xOrg(idx);" "; yOrg(idx)+menu.offset;" ";xOrg(idx); " "; yOrg(idx)+20+menu.offset ;
    result = postRender(idx, displayOrdering,menu.offset)
    return

[renderTextEdit] 'render the textedit at idx. type$(idx) = "textedit"
    fillIt$ = "white"
    if texteditDefaultColor$ <> "" then fillIt$ =  texteditDefaultColor$
    if boxcolor$(idx) <> "" then fillIt$ = boxcolor$(idx)
    print #form, "place "; xOrg(idx); " "; yOrg(idx) +menu.offset;
    print #form, "color white ; backcolor ";fillIt$;" ; size 1" ;
    print #form, "down ; boxfilled "; xOrg(idx)+width(idx)+1; " "; yOrg(idx)+height(idx)+1 +menu.offset;
    print #form, "color buttonface ; size 1" ;
    print #form, "down ; box "; xOrg(idx)+width(idx)-1; " "; yOrg(idx)+height(idx)+menu.offset ;
    print #form, "color buttonface ; backcolor buttonface" ;
    print #form, "place "; xOrg(idx)+width(idx)-18; " "; yOrg(idx)+menu.offset;
    print #form, "boxfilled "; xOrg(idx)+width(idx); " "; yOrg(idx)+height(idx)-17 +menu.offset;
    print #form, "drawbmp scrollUp "; xOrg(idx)+width(idx)-17; " "; yOrg(idx)+menu.offset;
    print #form, "drawbmp scrollDown "; xOrg(idx)+width(idx)-17; " "; yOrg(idx)+height(idx)-35+menu.offset;
    print #form, "place "; xOrg(idx); " "; yOrg(idx)+height(idx)-18+menu.offset;
    print #form, "boxfilled "; xOrg(idx)+width(idx); " "; yOrg(idx)+height(idx)+menu.offset ;
    print #form, "color darkgray ; backcolor white ; size 2" ;
    print #form, "down ; line "; xOrg(idx);" "; yOrg(idx)+menu.offset;" ";xOrg(idx)+width(idx); " "; yOrg(idx)+menu.offset ;
    print #form, "down ; line "; xOrg(idx);" "; yOrg(idx)+menu.offset;" ";xOrg(idx); " "; yOrg(idx)+height(idx)+menu.offset ;
    print #form, "drawbmp scrollLeft "; xOrg(idx)+1; " "; yOrg(idx)+height(idx)-17+menu.offset;
    print #form, "drawbmp scrollRight "; xOrg(idx)+width(idx)-33; " "; yOrg(idx)+height(idx)-17+menu.offset;
    result = postRender(idx, displayOrdering,menu.offset)
    return

[renderListBox] 'render the listbox at idx. type$(idx) = "listbox"
    fillIt$ = "white"
    if windowListboxColor$ <> "" then fillIt$ = windowListboxColor$ 
    if boxcolor$(idx) <> "" then fillIt$ = boxcolor$(idx)
    print #form, "place "; xOrg(idx); " "; yOrg(idx)+menu.offset ;
    print #form, "color white ; backcolor ";fillIt$;" ; size 1" ;
    print #form, "down ; boxfilled "; xOrg(idx)+width(idx)+1; " "; yOrg(idx)+height(idx)+1 +menu.offset;
    print #form, "color buttonface ; size 1" ;
    print #form, "down ; box "; xOrg(idx)+width(idx)-1; " "; yOrg(idx)+height(idx)+menu.offset ;
    print #form, "color buttonface ; backcolor buttonface" ;
    print #form, "place "; xOrg(idx)+width(idx)-18; " "; yOrg(idx)+menu.offset;
    print #form, "boxfilled "; xOrg(idx)+width(idx); " "; yOrg(idx)+height(idx)+menu.offset ;
    print #form, "color darkgray ; backcolor white ; size 2" ;
    print #form, "down ; line "; xOrg(idx);" "; yOrg(idx)+menu.offset;" ";xOrg(idx)+width(idx); " "; yOrg(idx)+menu.offset ;
    print #form, "down ; line "; xOrg(idx);" "; yOrg(idx)+menu.offset;" ";xOrg(idx); " "; yOrg(idx)+height(idx)+menu.offset ;
    print #form, "drawbmp scrollUp "; xOrg(idx)+width(idx)-17; " "; yOrg(idx)+menu.offset+1;
    print #form, "drawbmp scrollDown "; xOrg(idx)+width(idx)-17; " "; yOrg(idx)+height(idx)-18+menu.offset;
    result = postRender(idx, displayOrdering,menu.offset)
    return

[renderGraphicBox] 'render the graphicbox at idx.  type$(idx) = "graphicbox"
'  assume a font 8x15
    print #form, "place "; xOrg(idx); " "; yOrg(idx)+menu.offset;
    print #form, "color black ; backcolor "; boxcolor$(idx) ;"; size 1" ;
    if Platform$ = "OS/2" then print #form, "backcolor palegray" ;
    print #form, "down ; boxfilled "; xOrg(idx)+width(idx); " "; yOrg(idx)+height(idx)+menu.offset;
    result = postRender(idx, displayOrdering,menu.offset)
    return

[renderGroupBox] 'render the groupbox at idx.  type$(idx) = "groupbox"
    'assume a font 8x15.
    print #form, "place "; xOrg(idx); " "; yOrg(idx)+ 5+menu.offset ;
    print #form, "color ";currentForegroundColor$;" ; backcolor ";currentBackgroundColor$;" ; size 1" ;
    if Platform$ = "OS/2" then print #form, "backcolor palegray" ;
    print #form, "down ; boxfilled "; xOrg(idx)+width(idx); " "; yOrg(idx)+height(idx)+menu.offset ;
    print #form, "place "; xOrg(idx)+8; " "; yOrg(idx)+10+menu.offset ;
    print #form, "color ";currentForegroundColor$;";\"; label$(idx);
    result = postRender(idx, displayOrdering,menu.offset)
    return

[setForSelection] 'set up event handling for the default behavior (selection)
'check handle here for redraw
    print #form, "when leftButtonDown [selectControl]";
    if menuEdit = 0 then print #form, "when leftButtonDouble [inspectControl]";
    if menuEdit = 1 then print #form, "when leftButtonDouble [editMenus]";
    print #form, "when rightButtonUp [popupMenu]";
    print #form, "when leftButtonMove" ;
    print #form, "when leftButtonUp" ;
    wait

[selectControl] 'set up event handling
'"fix" form if it has been covered by another application.
    if h<>hParent then
        h=Parent
        if newIndex>0 then
            newIndex=0
            gosub [redrawAll]
            gosub [deselectOnly]
        end if
        wait
    end if
    print #form, "when leftButtonUp [setForSelection]" ;
    print #form, "when leftButtonDown" ;
    'highlight the control at the mouse click position
    x = MouseX : y = MouseY
    if index = 0 then [dontDeselect]
    'check to see if the resize handle has been clicked on, if applicable
    if instr(resizeable$, type$(index)) = 0 then [deselect]
    if index = 1 then
        if x > xOrg(index)+(width(index)/2)-4 and x < ((xOrg(index))+(width(index)/2))+4 and y > yOrg(index)+height(index)-4 and y < yOrg(index)+height(index)+4 then [resizeControlX]
        if x > xOrg(index)+width(index)-4 and x < xOrg(index)+width(index)+4 and y > yOrg(index)+(height(index)/2)-4 and y < yOrg(index)+(height(index)/2)+4 then [resizeControlY]
        if x > xOrg(index)+width(index)-4 and x < xOrg(index)+width(index)+4 and y > yOrg(index)+height(index)-4 and y < yOrg(index)+height(index)+4 then [resizeControl]
    else
        if x > xOrg(index)+(width(index)/2)-4 and x < xOrg(index)+(width(index)/2)+4 and y > yOrg(index)+height(index)-4+menu.offset and y < yOrg(index)+height(index)+4+menu.offset then [resizeControlX]
        if x > xOrg(index)+width(index)-4 and x < xOrg(index)+width(index)+4 and y > yOrg(index)+(height(index)/2)-4+menu.offset and y < yOrg(index)+(height(index)/2)+4+menu.offset then [resizeControlY]
        if x > xOrg(index)+width(index)-4 and x < xOrg(index)+width(index)+4 and y > yOrg(index)+height(index)-4+menu.offset and y < yOrg(index)+height(index)+4+menu.offset then [resizeControl]
    end if
    goto [deselect]

[deselect] ' Deselect control
    print #form, "delsegment "; selectId -1 ;
    gosub [selectDeselect]
    index = 0
    print #form, "delsegment "; selectId - 1 ;

[dontDeselect] ' Select control
    gosub [determineControl]
    if newIndex = 0 then [setUpMovementEvent]
    index = newIndex
    toolsIndex = newIndex
    gosub [selectDeselect]
    lastMouseX = MouseX
    lastMouseY = MouseY

[setUpMovementEvent] ' Prepare to drag control
     gosub [checkPosition]
    if type$(newIndex) = "windowframe" then wait
    print #form, "when leftButtonMove [beginObjectMove]" ;
    wait

[determineControl] 'based on x/y, determine which control is selected
    'set newIndex to point to this control, if found
    'otherwise set newIndex to 0
    newIndex = 0
    menuEdit = 0
    if menuCount > 0 and _
        y < yOrg(1)+menu.offset+25 and _
        x > xOrg(1) and _
        x < xOrg(1)+width(1) then menuEdit = 1
    if objectCount = 0 then return
    for i = objectCount to 1 step -1
        if newIndex > 0 then [skipControl]
        if type$(i) = "" then [skipControl]
        if x < xOrg(i) or x > xOrg(i)+width(i) then [skipControl]
        if y < yOrg(i)+menu.offset or y > yOrg(i)+height(i)+menu.offset then [skipControl]
        newIndex = i
        i = 1

[skipControl] ' Skip control
    next i
    return

[selectDeselect] ' Draw handles around controls
    'select or deselect the object at index by drawing handles
    xOrgIdx = xOrg(index)
    if index <> 1 then yOrgIdx = yOrg(index)+menu.offset else yOrgIdx = yOrg(index)
    xow = xOrgIdx+width(index)
    yoh = yOrgIdx+height(index)
    print #form, "rule xor ; down";
    if type$(index) = "windowframe" then [drawSizingHandle]
    print #form, "color black ; backcolor white" ;
    if currentBackgroundColor$ = "black" then print #form, "color yellow ; backcolor white" ;
    print #form, "place "; xOrgIdx-4; " "; yOrgIdx-4 ;
    print #form, "boxfilled "; xOrgIdx+4; " "; yOrgIdx+4 ;
    print #form, "place "; xow-4; " "; yOrgIdx-4 ;
    print #form, "boxfilled "; xow+4; " "; yOrgIdx+4 ;
    print #form, "place "; xOrgIdx-4; " "; yoh-4 ;
    print #form, "boxfilled "; xOrgIdx+4; " "; yoh+4 ;

[drawSizingHandle] ' Draw sizing handle
    gosub [checkPosition]

    if instr(resizeable$, type$(index)) > 0 then print #form, "backcolor black" ;
    print #form, "place "; xow-4; " "; yoh-4 ;
    print #form, "boxfilled "; xow+4; " "; yoh+4 ;
    print #form, "place "; (((xOrgIdx/2)+(xow/2)))-4; " "; yoh-4 ;
    print #form, "boxfilled "; ((xOrgIdx/2+(xow/2)))+4; " "; yoh+4 ;
    print #form, "place "; xow-4; " "; (yOrgIdx/2)+(yoh/2)-4 ;
    print #form, "boxfilled "; xow+4; " "; (yOrgIdx/2)+(yoh/2)+4 ;
    print #form, "rule over ; flush" ;
    print #form, "segment" ;
    input #form, selectId
    return

[deselectOnly]  'if there is a selected control, deselect it
    if index = 0 then return  'nothing is selected, do nothing
    print #form, "delsegment "; selectId -1 ;
    gosub [selectDeselect]
    index = 0
    print #form, "delsegment "; selectId - 1 ;
    return

[beginObjectMove] 'if the mouse has only slightly moved, ignore the event
    if abs(MouseX - x) < 3 and abs(MouseY - y) < 3 then [inputLoop]
    'set up to begin moving the selected object
    print #form, "delsegment "; selectId - 1 ;
    print #form, "when leftButtonMove [additionalObjectMoves]" ;
    print #form, "when leftButtonUp [acceptMovement]" ;

[additionalObjectMoves] 'adjust the position of the selected object, then draw an object frame the size of the
    'selected object at that new position using xor rule.  set event handling to manage
    'additional movements or termination of this object's movement.
    gosub [snapMouse] ' OK
    if MouseX = lastMouseX and MouseY = lastMouseY then wait '[inputLoop]
    gosub [eraseObjectFrame]
    xOrg(index) = xOrg(index) + (MouseX - lastMouseX)
    yOrg(index) = yOrg(index) + (MouseY - lastMouseY)
    gosub [snapXY] ' OK
    lastMouseX = MouseX
    lastMouseY = MouseY
    print #form, "color black ; backcolor white ; size 1" ;
    print #form, "place "; xOrg(index); " "; yOrg(index)+menu.offset;
    print #form, "down ; rule xor ; box "; xOrg(index)+width(index); " "; yOrg(index)+height(index)+menu.offset;
    print #form, "rule over ; up ; flush" ;
    print #form, "segment" : input #form, id
    print #form, "delsegment "; id - 1 ;
    wait

[eraseObjectFrame] 'erase the object frame (for movement)
    print #form, "color black ; backcolor white ; size 1" ;
    if index = 1 then
        print #form, "place "; xOrg(index); " "; yOrg(index);
        print #form, "down ; rule xor ; box "; xOrg(index)+width(index); " "; yOrg(index)+height(index);
    else
        print #form, "place "; xOrg(index); " "; yOrg(index)+menu.offset;
        print #form, "down ; rule xor ; box "; xOrg(index)+width(index); " "; yOrg(index)+height(index)+menu.offset;
    end if
    print #form, "rule over ; up ; flush" ;
    print #form, "segment" : input #form, id
    print #form, "delsegment "; id - 1 ;
    return

[acceptResizing] ' Resizing done, apply changes
    cursor normal
    if width(index) < 25 then width(index) = 25
    if type$(index) <> "textbox" and height(index) < 20 then height(index) = 20
    if type$(index) = "textbox" and height(index) < 25 then height(index) = 25
    if type$(index) <> "windowframe" then [acceptMovement]
    if width(index) < 100 then width(index) = 100
    if height(index) < 50 then height(index) = 50
    windowXExtent = width(index)
    windowYExtent = height(index)

[acceptMovement] 'end the movement phase, and redraw all objects
    print #form, "delsegment "; segment(index) - 1 ;
    gosub [redrawAll]
    gosub [selectDeselect]
    firstObjectMove = false
    goto [setForSelection]

[moveLeft] ' move control left in response to left arrow keypress
    if index < 2 or objectCount < 2 then [inputLoop]
    xOrg(index) = xOrg(index) - xInterval
    oldIndex = index
    gosub [redrawAll]
    index = oldIndex
    gosub [selectDeselect]
     wait

[moveRight] ' move control right in response to right arrow keypress
    if index < 2 or objectCount < 2 then [inputLoop]
    xOrg(index) = xOrg(index) + xInterval
    oldIndex = index
    gosub [redrawAll]
    index = oldIndex
    gosub [selectDeselect]
    wait

[moveUp] ' move control up in response to up arrow keypress
    if index < 2 or objectCount < 2 then [inputLoop]
    yOrg(index) = yOrg(index) - yInterval
    oldIndex = index
    gosub [redrawAll]
    index = oldIndex
    gosub [selectDeselect]
    wait

[moveDown] ' move control down in response to right arrow keypress
    if index < 2 or objectCount < 2 then [inputLoop]
    yOrg(index) = yOrg(index) + yInterval
    oldIndex = index
    gosub [redrawAll]
    index = oldIndex
    gosub [selectDeselect]
    wait

[resizeControlX] 'set up to begin resizing the selected object X only
    cursor crosshair
    firstObjectMove = true
    oldwidth = width(index)
    oldheight = height(index) ' for bmpbutton stretch only
    print #form, "delsegment "; selectId - 1 ;
    print #form, "when leftButtonMove [additionalResizesX]" ;
    print #form, "when leftButtonUp [acceptResizing]" ;
    gosub [snapMouse]
    lastMouseY = MouseY

[additionalResizesX] 'adjust the position of the selected object, then draw an object frame the size of the
    'selected object at that new position using xor rule.  set event handling to manage
    'additional movements or termination of this object's movement.
    if firstObjectMove = false then gosub [eraseObjectFrame]
    gosub [snapMouse]
    height(index) = height(index) + (MouseY - lastMouseY)
    gosub [snapWH]
    lastMouseY = MouseY
    print #form, "color black ; backcolor white ; size 1" ;
    if index = 1 then
        print #form, "place "; xOrg(index); " "; yOrg(index);
        print #form, "down ; rule xor ; box "; xOrg(index)+width(index); " "; yOrg(index)+height(index);
    else
        print #form, "place "; xOrg(index); " "; yOrg(index) +menu.offset;
        print #form, "down ; rule xor ; box "; xOrg(index)+width(index); " "; yOrg(index)+height(index)+menu.offset;
    end if
    print #form, "rule over ; up ; flush" ;
    print #form, "segment id"
    print #form, "delsegment id"
    wait

[resizeControlY] 'set up to begin resizing the selected object X only
    cursor crosshair
    firstObjectMove = true
    oldwidth = width(index)
    oldheight = height(index) ' for bmpbutton stretch only
    print #form, "delsegment "; selectId - 1 ;
    print #form, "when leftButtonMove [additionalResizesY]" ;
    print #form, "when leftButtonUp [acceptResizing]" ;
    gosub [snapMouse]
    lastMouseX = MouseX

[additionalResizesY] 'adjust the position of the selected object, then draw an object frame the size of the
    'selected object at that new position using xor rule.  set event handling to manage
    'additional movements or termination of this object's movement.
    if firstObjectMove = false then gosub [eraseObjectFrame]
    gosub [snapMouse]
    width(index) = width(index) + (MouseX - lastMouseX)
    gosub [snapWH]
    lastMouseX = MouseX
    print #form, "color black ; backcolor white ; size 1" ;
    if index = 1 then
        print #form, "place "; xOrg(index); " "; yOrg(index);
        print #form, "down ; rule xor ; box "; xOrg(index)+width(index); " "; yOrg(index)+height(index);
    else
        print #form, "place "; xOrg(index); " "; yOrg(index) +menu.offset;
        print #form, "down ; rule xor ; box "; xOrg(index)+width(index); " "; yOrg(index)+height(index)+menu.offset;
    end if
    print #form, "rule over ; up ; flush" ;
    print #form, "segment" : input #form, id
    print #form, "delsegment "; id - 1 ;
    wait

[resizeControl] 'set up to begin resizing the selected object
    cursor crosshair
    firstObjectMove = true
    oldwidth = width(index)
    oldheight = height(index) ' for bmpbutton stretch only
    print #form, "delsegment "; selectId - 1 ;
    print #form, "when leftButtonMove [additionalResizes]" ;
    print #form, "when leftButtonUp [acceptResizing]" ;
    gosub [snapMouse]
    lastMouseX = MouseX
    lastMouseY = MouseY

[additionalResizes] 'adjust the position of the selected object, then draw an object frame the size of the
    'selected object at that new position using xor rule.  set event handling to manage
    'additional movements or termination of this object's movement.
    if firstObjectMove = false then gosub [eraseObjectFrame]
    gosub [snapMouse]
    width(index) = width(index) + (MouseX - lastMouseX)
    height(index) = height(index) + (MouseY - lastMouseY)
    gosub [snapWH]
    lastMouseX = MouseX
    lastMouseY = MouseY
    print #form, "color black ; backcolor white ; size 1" ;
    if index = 1 then
        print #form, "place "; xOrg(index); " "; yOrg(index);
        print #form, "down ; rule xor ; box "; xOrg(index)+width(index); " "; yOrg(index)+height(index);
    else
        print #form, "place "; xOrg(index); " "; yOrg(index) +menu.offset;
        print #form, "down ; rule xor ; box "; xOrg(index)+width(index); " "; yOrg(index)+height(index)+menu.offset;
    end if
    print #form, "rule over ; up ; flush" ;
    print #form, "segment" : input #form, id
    print #form, "delsegment "; id - 1 ;
    wait

[snapMouse]  'if snapOn is selected, then snap the mouse to grid
    gosub [checkPosition]
    if snapOn = 0 then return
    MouseX = int((MouseX + int(xInterval / 2)) / xInterval) * xInterval
    MouseY = int((MouseY + int(yInterval / 2)) / yInterval) * yInterval
    return

[snapWH]  'if snapOn is selected, then snap the width & height to grid
    if snapOn = 0 then return
    width(index)  = int((width(index)  + int(xInterval / 2)) / xInterval) * xInterval
    height(index) = int((height(index) + int(yInterval / 2)) / yInterval) * yInterval
    return

[snapXY]  'if snapOn is selected, then snap the x,y position to grid
    if snapOn = 0 then return
    xOrg(index)   = int((xOrg(index)   + int(xInterval / 2)) / xInterval) * xInterval
    yOrg(index)   = int((yOrg(index)   + int(yInterval / 2)) / yInterval) * yInterval
    return

[redrawAll] 'redraw all controls
    isModified = 1  'the form has been modified
    print #form, "cls"
    index = 0
    gosub [renderWindow]
    if gridVisibleOn = 1 then gosub [displayGrid]
    if objectCount = 0 then return
    'If it is graphic window, foreground and background colors don't work!
    if left$(windowType$,7) = "graphic" then
        oldForegroundColor$ = currentForegroundColor$
        oldBackgroundColor$ = currentBackgroundColor$
        currentForegroundColor$ = "black"
        currentBackgroundColor$ = "white"
    end if
    for idx = 1 to objectCount ' initalize combobox under all controls
        typeIdx$ = type$(idx)
        if typeIdx$ = "combobox"  then
        gosub [renderComboBox]
        if comboStatus=1 then comboStatus=0:gosub [keepInBack2]'    : goto [redrawNext]
        end if
   next idx
    for idx = 1 to objectCount ' Groupboxes always under all other controls except texteditors
        typeIdx$ = type$(idx)
        if typeIdx$ = "groupbox" then gosub [renderGroupBox]:gosub [keepInBack2]
    next idx
    for idx = 1 to objectCount ' Graphicboxes always on bottom
        typeIdx$ = type$(idx)
        if typeIdx$ = "graphicbox" then gosub [renderGraphicBox]
    next idx
    for idx = 1 to objectCount ' Texteditors always under all controls
        typeIdx$ = type$(idx)
        if typeIdx$ = "textedit" then gosub [renderTextEdit]
    next idx
    for idx = 1 to objectCount
        typeIdx$ = type$(idx)
        if typeIdx$ = "combobox"    then gosub [renderComboBox]    : goto [redrawNext]
        if typeIdx$ = "textbox"     then gosub [renderTextBox]     : goto [redrawNext]
        if typeIdx$ = "statictext"  then gosub [renderStaticText]  : goto [redrawNext]
        if typeIdx$ = "button"      then gosub [renderButton]      : goto [redrawNext]
        if typeIdx$ = "listbox"     then gosub [renderListBox]     : goto [redrawNext]
        if typeIdx$ = "bmpbutton"   then gosub [renderBmpButton]   : goto [redrawNext]
        if typeIdx$ = "radiobutton" then gosub [renderRadioButton] : goto [redrawNext]
        if typeIdx$ = "checkbox"    then gosub [renderCheckBox]    : goto [redrawNext]
      [redrawNext]
    next idx
    gosub [clipControls]
    if left$(windowType$,7) = "graphic" then ' restore settings in case window type changes
        currentForegroundColor$ = oldForegroundColor$
        currentBackgroundColor$ = oldBackgroundColor$
    end if
    print #form, "down;flush"
    return

[keepInBack2] 'Keep groupbox in behind all other controls.
    tDex=idx
    tmpType$        = type$(tDex)
    tmpLabel$       = label$(tDex)
    tmpNames$       = names$(tDex)
    tmpXOrigin      = xOrg(tDex)
    tmpYOrigin      = yOrg(tDex)
    tmpWidth        = width(tDex)
    tmpHeight       = height(tDex)
    tmpCorner$      = corner$(tDex)
    tmpBranchLabel$ = branchLabel$(tDex)
    tmpSegment      = segment(tDex)
    tmpHandle$      = handle$(tDex)
    tmpBmpName$     = bmpName$(tDex)
    tmpBmpFileName$ = bmpFileName$(tDex)
    tmpArrayName$   = arrayName$(tDex)
    tmpTooltip$     = tooltip$(tDex)
    tmpBoxcolor$    = boxcolor$(tDex)
    for kiB = tDex - 1 to 2 step -1
        type$(kiB+1)        = type$(kiB)
        label$(kiB+1)       = label$(kiB)
        names$(kiB+1)       = names$(kiB)
        xOrg(kiB+1)         = xOrg(kiB)
        yOrg(kiB+1)         = yOrg(kiB)
        width(kiB+1)        = width(kiB)
        height(kiB+1)       = height(kiB)
        corner$(kiB+1)      = corner$(kiB)
        branchLabel$(kiB+1) = branchLabel$(kiB)
        segment(kiB+1)      = segment(kiB)
        handle$(kiB+1)      = handle$(kiB)
        bmpName$(kiB+1)     = bmpName$(kiB)
        bmpFileName$(kiB+1) = bmpFileName$(kiB)
        arrayName$(kiB+1)   = arrayName$(kiB)
        tooltip$(kiB+1)     = tooltip$(kiB)
        boxcolor$(kiB+1)    = boxcolor$(kiB)
    next kiB
    type$(2)        = tmpType$
    label$(2)       = tmpLabel$
    names$(2)       = tmpNames$
    xOrg(2)         = tmpXOrigin
    yOrg(2)         = tmpYOrigin
    width(2)        = tmpWidth
    height(2)       = tmpHeight
    corner$(2)      = tmpCorner$
    branchLabel$(2) = tmpBranchLabel$
    segment(2)      = tmpSegment
    handle$(2)      = tmpHandle$
    bmpName$(2)     = tmpBmpName$
    bmpFileName$(2) = tmpFileBmpName$
    arrayName$(2)   = tmpArrayName$
    tooltip$(2)     = tmpTooltip$
    boxcolor$(2)    = tmpBoxcolor$
    tDex = 0
[breakKeepInBack]
    return

[displayGrid] ' Draw a grid on screen that corresponds to snapx and snapy values
    lineColor$ = "white"
    if currentBackgroundColor$ = "white" then lineColor$ = "darkgray"
    titlebarOffset = 20
    for yShowGrid = windowYOrigin+3+menu.offset+titlebarOffset to windowYOrigin+windowYExtent-5 step yInterval '*2
            lines$ = "down;size 1;color "+lineColor$+"; line "+str$(windowXOrigin)+" "+str$(yShowGrid)+" "+str$(windowXOrigin+windowXExtent-3)+" "+str$(yShowGrid)
            print #form, lines$
    next yShowGrid
    for xShowGrid = windowXOrigin-xInterval+3 to windowXOrigin+windowXExtent-1 step xInterval '*2
        lines$ = "down;size 1;color "+lineColor$+"; line "+str$(xShowGrid)+" "+str$(windowYOrigin+5+menu.offset+titlebarOffset)+" "+str$(xShowGrid)+" "+str$(windowYOrigin+windowYExtent-3)
        print #form, lines$
    next xShowGrid
    return

[clipControls] 'erase any controls outside of window:
    xOrg = windowXOrigin
    yOrg = windowYOrigin
    xExt = windowXExtent
    yExt = windowYExtent
    print #form, "color 255 250 230;backcolor 255 250 230"
    print #form, "down"
    print #form, "place 0 ";yExt+yOrg
    print #form, "boxfilled 2000 2000"
    print #form, "place ";xExt+xOrg;" 0"
    print #form, "boxfilled 2000 2000";
    print #form, "place 0 0"
    print #form, "boxfilled ";xOrg;" 2000"
    if makeStatusbar = 1 then  'Draw statusbar
        print #form, "color buttonface;backcolor buttonface;place ";xOrg+4;" ";yOrg+yExt-5;";boxfilled ";xOrg+xExt-4;" ";yOrg+yExt-25;
        print #form, "color white;place ";xOrg+4;" ";yOrg+yExt-5;";box ";xOrg+xExt-4;" ";yOrg+yExt-25;
        print #form, "color darkgray";
        print #form, "line ";xOrg+4;" ";yOrg+yExt-25;" ";xOrg+xExt-5;" ";yOrg+yExt-25;
        print #form, "line ";xOrg+4;" ";yOrg+yExt-25;" ";xOrg+4;" ";yOrg+yExt-5;
        print #form, "color white;size 1";
        print #form, "line ";xOrg+xExt-19;" ";yOrg+yExt-5;" ";xOrg+xExt-4;" ";yOrg+yExt-20;
        print #form, "color darkgray;size 1";
        print #form, "line ";xOrg+xExt-18;" ";yOrg+yExt-5;" ";xOrg+xExt-4;" ";yOrg+yExt-19;
        print #form, "color white;size 1";
        print #form, "line ";xOrg+xExt-13;" ";yOrg+yExt-5;" ";xOrg+xExt-4;" ";yOrg+yExt-14;
        print #form, "color darkgray;size 1";
        print #form, "line ";xOrg+xExt-12;" ";yOrg+yExt-5;" ";xOrg+xExt-4;" ";yOrg+yExt-13;
        print #form, "color white;size 1";
        print #form, "line ";xOrg+xExt-7;" ";yOrg+yExt-5;" ";xOrg+xExt-4;" ";yOrg+yExt-8;
        print #form, "color darkgray;size 1";
        print #form, "line ";xOrg+xExt-6;" ";yOrg+yExt-5;" ";xOrg+xExt-4;" ";yOrg+yExt-7;
    end if
    gosub [renderToolbox]
    return

[moveToBack] 'move the selected control to the back (first item drawn)
    if index < 2 or objectCount < 2 then [inputLoop]
    if index = 2 then gosub [redrawAll] : goto [inputLoop]
    tmpType$ = type$(index)
    tmpLabel$ = label$(index)
    tmpNames$ = names$(index)
    tmpXOrigin = xOrg(index)
    tmpYOrigin = yOrg(index)
    tmpWidth = width(index)
    tmpHeight = height(index)
    tmpCorner$ = corner$(index)
    tmpBranchLabel$ = branchLabel$(index)
    tmpSegment = segment(index)
    tmpHandle$ = handle$(index)
    tmpBmpName$ = bmpName$(index)
    tmpBmpFileName$ = bmpFileName$(index)
    tmpArrayName$ = arrayName$(index)
    tmpTooltip$ = tooltip$(index)
    tmpBoxcolor$ = boxcolor$(index)
    for idx = index - 1 to 2 step -1
        type$(idx+1) = type$(idx)
        label$(idx+1) = label$(idx)
        names$(idx+1) = names$(idx)
        xOrg(idx+1) = xOrg(idx)
        yOrg(idx+1) = yOrg(idx)
        width(idx+1) = width(idx)
        height(idx+1) = height(idx)
        corner$(idx+1) = corner$(idx)
        branchLabel$(idx+1) = branchLabel$(idx)
        segment(idx+1) = segment(idx)
        handle$(idx+1) = handle$(idx)
        bmpName$(idx+1) = bmpName$(idx)
        bmpFileName$(idx+1) = bmpFileName$(idx)
        arrayName$(idx+1) = arrayName$(idx)
        tooltip$(idx+1) = tooltip$(idx)
        boxcolor$(idx+1) = boxcolor$(idx)
    next idx
    type$(2) = tmpType$
    label$(2) = tmpLabel$
    names$(2) = tmpNames$
    xOrg(2) = tmpXOrigin
    yOrg(2) = tmpYOrigin
    width(2) = tmpWidth
    height(2) = tmpHeight
    corner$(2) = tmpCorner$
    branchLabel$(2) = tmpBranchLabel$
    segment(2) = tmpSegment
    handle$(2) = tmpHandle$
    bmpName$(2) = tmpBmpName$
    bmpFileName$(2) = tmpFileBmpName$
    arrayName$(2) = tmpArrayName$
    tooltip$(2) = tmpTooltip$
    boxcolor$(2) = tmpBoxcolor$
    gosub [redrawAll]
    index = 0 'necessary here
    wait

[moveToFront] 'move the selected control to the front (last item drawn)
    if index < 2 or objectCount < 2 then [inputLoop]
    if index = objectCount then gosub [redrawAll] : goto [inputLoop]
    tmpType$ = type$(index)
    tmpLabel$ = label$(index)
    tmpNames$ = names$(index)
    tmpXOrigin = xOrg(index)
    tmpYOrigin = yOrg(index)
    tmpWidth = width(index)
    tmpHeight = height(index)
    tmpCorner$ = corner$(index)
    tmpBranchLabel$ = branchLabel$(index)
    tmpSegment = segment(index)
    tmpHandle$ = handle$(index)
    tmpBmpName$ = bmpName$(index)
    tmpBmpFileName$ = bmpFileName$(index)
    tmpArrayName$ = arrayName$(index)
    tmpTooltip$ = tooltip$(index)
    tmpBoxcolor$ = boxcolor$(index)
    for idx = index to objectCount - 1
        type$(idx) = type$(idx+1)
        label$(idx) = label$(idx+1)
        names$(idx) = names$(idx+1)
        xOrg(idx) = xOrg(idx+1)
        yOrg(idx) = yOrg(idx+1)
        width(idx) = width(idx+1)
        height(idx) = height(idx+1)
        corner$(idx) = corner$(idx+1)
        branchLabel$(idx) = branchLabel$(idx+1)
        segment(idx) = segment(idx+1)
        handle$(idx) = handle$(idx+1)
        bmpName$(idx) = bmpName$(idx+1)
        bmpFileName$(idx) = bmpFileName$(idx+1)
        arrayName$(idx) = arrayName$(idx+1)
        tooltip$(idx) = tooltip$(idx+1)
        boxcolor$(idx) = boxcolor$(idx+1)
    next idx
    type$(objectCount) = tmpType$
    label$(objectCount) = tmpLabel$
    names$(objectCount) = tmpNames$
    xOrg(objectCount) = tmpXOrigin
    yOrg(objectCount) = tmpYOrigin
    width(objectCount) = tmpWidth
    height(objectCount) = tmpHeight
    corner$(objectCount) = tmpCorner$
    branchLabel$(objectCount) = tmpBranchLabel$
    segment(objectCount) = tmpSegment
    handle$(objectCount) = tmpHandle$
    bmpName$(objectCount) = tmpBmpName$
    bmpFileName$(objectCount) = tmpFileBmpName$
    arrayName$(objectCount) = tmpArrayName$
    tooltip$(objectCount) = tmpTooltip$
    boxcolor$(objectCount) = tmpBoxcolor$
    gosub [redrawAll]
    gosub [selectDeselect]
    wait

[deleteControl] 'delete the selected control
    if index < 2 then [inputLoop]
    'delete graphical segments and clean up display
    print #form, "delsegment "; selectId -1 ;
    gosub [selectDeselect]
    print #form, "delsegment "; selectId - 1 ;
    if bmpFileName$<>"" then bmpCount = bmpCount -1
    if type$(index) = "textedit" then
        textEditControl=textEditControl-1
        if textEditControl=0 then    'remove edit menu item if this is last
            for menuX = 1 to menuCount 'textedit
                if menu$(menuX) ="Edit" and menuItemCount(menuX)=0 then menDex=menuX
            next menuX
            for x = menDex to menuCount
                menu$(x) = menu$(x+1)
                menuItemCount(x)=menuItemCount(x+1)
            next x
            for y = menDex to menuCount
                for x = 0 to 29
                    menuItem$(y,x) = menuItem$(y+1,x)
                next x
            next y
            for x = 0 to 29
                menuItem$(menuCount, x) = ""
            next x
            menuCount=menuCount-1
            if menuCount=0 then menu.offset=0
        end if
    end if
    for idx = index to objectCount
        type$(idx) = type$(idx+1)
        label$(idx) = label$(idx+1)
        names$(idx) = names$(idx+1)
        xOrg(idx) = xOrg(idx+1)
        yOrg(idx) = yOrg(idx+1)
        width(idx) = width(idx+1)
        height(idx) = height(idx+1)
        corner$(idx) = corner$(idx+1)
        branchLabel$(idx) = branchLabel$(idx+1)
        segment(idx) = segment(idx+1)
        handle$(idx) = handle$(idx+1)
        bmpName$(idx) = bmpName$(idx+1)
        bmpFileName$(idx) = bmpFileName$(idx+1)
        arrayName$(idx) = arrayName$(idx+1)
        tooltip$(idx) = tooltip$(idx+1)
        boxcolor$(idx) = boxcolor$(idx+1)
    next idx
    objectCount = objectCount - 1
    gosub [redrawAll]
    index = 0
    print #form, "setfocus";
    wait

[testCode] ' If user wants to test code with LB compiler, set flag
    testCode = 1

[produceCodeAndOutline] 'set a flag so that an outline will be added
    produceOutline = 1

[produceCode] 'produce code for the controls in the form
timer 0
    holdTextEditColor$=""
    holdComboBoxcolor$=""
    holdTextBoxColor$=""
    holdListboxColor$=""
    gosub [deselectOnly]
    gosub [checkPosition]
    if codeIsOpen = 1 then close #code : codeIsOpen = 0
    WindowWidth=450:WindowHeight=330
    UpperLeftX = DisplayWidth/2 - 450/2
    UpperLeftY = DisplayHeight/2 - 330/2
    open "Freeform 3 output window" for text as #code
    hWnd=hwnd(#code)
    codeIsOpen = 1
    print #code, "'Form created with the help of Freeform 3 v";ffVersion$
    print #code, "'Generated on ";date$();" at ";time$()
    print #code, ""
    print #code, ""
    print #code, "[setup." + mid$(winHandle$, 2) + ".Window]"
    print #code, ""
    print #code, "    '-----Begin code for ";winHandle$ 'mid$(winHandle$, 2)
    print #code, ""
    if produceOutline = 1 then print #code, "    nomainwin"
    print #code, "    WindowWidth = "; windowXExtent
    print #code, "    WindowHeight = "; windowYExtent
    if windowCenterOnScreen = 1 then
        print #code, "    UpperLeftX=int((DisplayWidth-WindowWidth)/2)"
        print #code, "    UpperLeftY=int((DisplayHeight-WindowHeight)/2)"
    else
        if windowUpperLeftX <> 0 then print #code, "    UpperLeftX = ";windowUpperLeftX
        if windowUpperLeftY <> 0 then print #code, "    UpperLeftY = ";windowUpperLeftY
    end if
    print #code, ""

'check for rgb here
    if left$(windowType$, 8) <> "graphics" then
   ' oldBgColor$    ="Auto" '"buttonface"
   ' oldFgColor$    ="Auto" ' "black"
   cbc$=currentBackgroundColor$
   cfc$=currentForegroundColor$
    if cbc$<>"buttonface" then _
    print #code, "    BackgroundColor$ = "; qu$; currentBackgroundColor$; qu$; ""

if cfc$<>"black" then _
    print #code, "    ForegroundColor$ = "; qu$; currentForegroundColor$; qu$; ""
else
'check to see if valid color
    bgOK=0
    fgOK=0
    GraphicBackgroundColor$=currentBackgroundColor$
    GraphicForegroundColor$=currentForegroundColor$
    for ct=1 to 18
        if currentBackgroundColor$=colorType$(ct) then bgOK=1
        if currentForegroundColor$=colorType$(ct) then fgOK=1
    next ct
    if bgOK=0 then GraphicBackgroundColor$="buttonface"
    if fgOK=0 then GraphicForegroundColor$="black"

    'if bgOK then  print #code, "    BackgroundColor$ = "; qu$; GraphicBackgroundColor$; qu$; ""
    'if fgOK then print #code, "    ForegroundColor$ = "; qu$; GraphicForegroundColor$; qu$; ""
end if
    if windowComboboxColor$<>""   then print #code, "    ComboboxColor$ = ";qu$;windowComboboxColor$;qu$
    if windowListboxColor$<>""    then print #code, "    ListboxColor$ = ";qu$;windowListboxColor$;qu$
    if windowTextboxColor$<>""    then print #code, "    TextboxColor$ = ";qu$;windowTextboxColor$;qu$
    if windowTexteditorColor$<>"" then print #code, "    TexteditorColor$ = ";qu$;windowTexteditorColor$;qu$
    if objectCount < 2 then [menuCode]
    print #code, ""
    print #code, "    '-----Begin GUI objects code"
    print #code, ""
    for x = objectCount to 2 step -1' Do graphicbox controls in reverse order so they display right
        code$ = ""
        if type$(x) = "graphicbox" then gosub [codeForType1]
        if code$ <> "" then print #code, code$
    next x
    for x = objectCount to 2 step -1' Do graphicbox controls in reverse order so they display right
        code$ = ""
        colorcode$ = ""
        if type$(x) = "textedit" and boxcolor$(x) <> "" then gosub [codeForTextEditColor]
        if type$(x) = "textedit" then
            gosub [codeForType1]
        end if
        if colorcode$<>"" then print #code, colorcode$
        if code$ <> "" then print #code, code$
    next x

    for x = objectCount to 2 step -1' Do graphicbox controls in reverse order so they display right
        code$ = ""
        if type$(x) = "groupbox" then gosub [codeForType2]
        if code$ <> "" then print #code, code$
    next x

    for x = 2 to objectCount ' Now make code for the rest of controls
        code$ = ""
        colorcode$ = ""
        colorcodeout$ = ""
        if type$(x) = "button" then gosub [codeForButton]
        if type$(x) = "combobox" and boxcolor$(x) <> "" then gosub [codeForComboBoxColor]
        if type$(x) = "combobox" then gosub [codeForType3]
        if type$(x) = "textbox" and boxcolor$(x) <> "" then gosub [codeForTextBoxColor]
        if type$(x) = "textbox" then gosub [codeForType1]
        if type$(x) = "listbox" and boxcolor$(x) <> "" then gosub [codeForListBoxColor]
        if type$(x) = "listbox" then gosub [codeForType3]
        if type$(x) = "bmpbutton" then gosub [codeForBmpButton]
        if type$(x) = "statictext" then gosub [codeForType2]
        if type$(x) = "radiobutton" then gosub [codeForType4]
        if type$(x) = "checkbox" then gosub [codeForType4]
        if colorcode$ <> "" then print #code, colorcode$
        if code$ <> "" then print #code, code$
    next x
    print #code, ""
    print #code, "    '-----End GUI objects code"
    print #code, ""

[menuCode]   'write menu code
    if menuCount = 0 then [noMenuCode]
    if left$(windowType$, 6) = "dialog" then
        print #code, "    '*** menus are not supported in windows of type "; windowType$; " ***"
        else
        print #code, "    '-----Begin menu code"
    end if
    print #code, ""
    for x = 1 to menuCount ' - 1
    if menuItemCount(x) > 0 then
        print #code, "    menu "; winHandle$; ", "; qu$; menu$(x); qu$;",_"
        mLen=len(winHandle$)+11
    else
        mTest$="    menu "+ winHandle$+", "+qu$+ menu$(x)+ qu$
        if menu$(x)="Edit" then
            print #code,mTest$;"  ' <-- Texteditor menu."
            print #code," "
        else
            print #code, mTest$;
            print #code, ", "; chr$(34); "&FixMe"; chr$(34);_
            ", [fixMe]  ' <-- this menu has no items!"
            print #code, " "
        end if
        goto [produceNextMenu]
    end if
'get len of longest item for current menu title
    baseX=0
    for yy = 0 to menuItemCount(x) - 1
        mi$ = menuItem$(x, yy)
        if left$(mi$,15)<>"---------------" then
             gf$=left$(mi$, instr(mi$, chr$(0)) - 1)
             gf=len(gf$)
             if gf>baseX then baseX=gf
        end if
    next yy

    for y = 0 to menuItemCount(x)-1
        brk=0
        mi$ = menuItem$(x, y)
        a=instr(mi$,chr$(0))+1
        l=len(mi$)
        for brl=a to l
            if mid$(mi$,brl,1)=chr$(0))then brk=brl
        next brl
        bmi$=right$(mi$,l-brk)
        mi$=left$(mi$,brk-1)

        mii$=menuItem$(x, y+1)
        a=instr(mii$,chr$(0))+1
        l=len(mii$)
        for brla=a to l ' while mid$(mi$,l,1)<>chr$(0)
            if mid$(mii$,brla,1)=chr$(0))then brk2=brla
        next brla
        mii$=left$(mii$,brk2-1)

        'Adjust len of current to match longest item len.
        currentItem$=left$(mi$, instr(mi$, chr$(0)) - 1)
        gk=baseX-len(currentItem$)
        'Check for seperator and add continuation character to menus.
        sep$=mid$(mii$, instr(mii$, chr$(0)) + 1)
        mbl$= mid$(mi$, instr(mi$, chr$(0)) + 1)
        if mbl$="[quit]" then mbl$="[quit.";mid$(winHandle$, 2);"]"
        mTest$=space$(mLen)+qu$+left$(mi$, instr(mi$, chr$(0)) - 1)+_
        qu$+space$(gk)+", "+ mbl$ 
        if  sep$<>"|" then
            if y< menuItemCount(x)-1 then mTest$=mTest$+",_"
            print #code, mTest$
        else
            print #code, mTest$;",|,_"
            y=y+1
        end if
    next y
        print #code, ""
      [produceNextMenu]
    next x
    print #code, ""
    print #code, "    '-----End menu code"
    print #code, ""

[noMenuCode] 'don't produce menu code
    if trim$(windowType$)="" then windowType$="window"
    print #code, "    open "; qu$; windowLabel$; qu$; " for "; windowType$; " as "; winHandle$

    for idx = 1 to objectCount
        if type$(idx) = "graphicbox" then  print #code, "    print ";winHandle$;".";names$(idx);", ";qu$;"down; fill "; boxcolor$(idx);"; flush";qu$ 
     next idx

    if left$(windowType$, 8) = "graphics" then
        print #code, "    print ";winHandle$;", ";qu$;"down;fill "; wincolor$;"; flush";qu$
        print #code, "    print ";winHandle$;", ";qu$;"color ";currentForegroundColor$;"; backcolor ";currentBackgroundColor$;qu$
        print #code, "    print ";winHandle$;", ";qu$;"font "; font$(1);qu$
    else
        print #code, "    print ";winHandle$;", ";qu$;"font "; font$(1);qu$
    end if
'============================================================
'add fonts for controls in graphics style GUIs
    for x = 1 to objectCount
        if trim$(font$(1))<>trim$(controlFont$(x)) or _
        left$(windowType$, 8) = "graphics" then
            if type$(x) = "button" or_
               type$(x) = "statictext" or _
               type$(x) = "textbox" or_
               type$(x) = "textedit" then
               print #code, "    print ";winHandle$;".";names$(x);", ";qu$;"!font ";controlFont$(x);qu$
               if  type$(x) = "checkbox" or_
                   type$(x) = "combobox" or_
                   type$(x) = "listbox"  or_
                   type$(x) = "radiobutton" then
                   print #code, "    print ";winHandle$;".";names$(x);", ";qu$;"font ";controlFont$(x);qu$
               end if
           end if
       end if
    next x
    'Add code for statusbar
    if makeStatusbar = 1  then
        print #code, ""
        print #code, "    '----Begin code for statusbar"
        print #code, ""
        print #code, "    h=hwnd(";winHandle$;")"
        if instr(windowType$,"graphics",0)>0 then
            print #code, "    CallDLL #user32, ";qu$;"GetParent";chr$(34);",_"
            print #code, "    h as long,_"
            print #code, "    hParent as long"
            print #code, ""

        end if
    print #code, "    value$ = "+qu$+"Put your statusbar message here.  Change it with [changeMessageBar]"+qu$
    print #code, "    styleValue = _WS_VISIBLE or _WS_CHILD"
    print #code, "    hStatusBar=initalizeStatusBar(h,value$)"

    if instr(windowType$,"window",0) > 0 and instr(windowType$,"graphics",0) = 0 then
        print #code, "    print ";winHandle$;", "+qu$+"resizehandler [resizeStatusbar]"+qu$
    end if
    print #code, ""
    print #code, "    '----End code for statusbar"
    print #code, ""
    end if
    makeTooltips = 0
    tooltipCount = 0
    for idx = 1 to objectCount
        if tooltip$(idx) <> "" then
            makeTooltips = 1
            idx = objectCount
        end if
    next idx
    if produceOutline = 1 then print #code, "    print ";winHandle$;", ";qu$;"trapclose [quit.";mid$(winHandle$, 2);"]";qu$
    'Add code for tooltips
    if makeTooltips = 1 and toolTipControl=1 then ttC=1 else ttC=0
    if makeTooltips = 1 and ttC=1 then
        print #code, ""
        print #code, "    '----Begin code for tooltips"
        print #code, ""
        print #code, "    'Struct for version info,"
        print #code, "    struct winOSver,_ "
        print #code, "    dwOSVersionInfoSize as long,_"
        print #code, "    dwMajorVersion as long,_"
        print #code, "    dwMinorVersion as long,_"
        print #code, "    dwBuildNumber as long,_"
        print #code, "    dwPlatformId as long,_"
        print #code, "    szCSDVersion as char[128]"
        print #code, ""
        print #code, "    'get the size (len) of the struct to input to the call"
        print #code, "    winOSver.dwOSVersionInfoSize.struct=len(winOSver.struct)"
        print #code, ""
        print #code, "    'do the call to fill the struct"
        print #code, "    calldll #kernel32,";chr$(34);"GetVersionExA";chr$(34);",_"
        print #code, "    winOSver as struct,_"
        print #code, "    result as void"
        print #code, "    'check the operating system version for enabling tooltips"
        print #code, "    if winOSver.dwPlatformId.struct <> 1 Then VERSION.FLAG = 1"
        print #code, ""
        dont=0
        if instr(windowType$,"graphics",0)>0 and makeStatusbar=1 then dont=1
        if dont=0 then
            print #code,"    hParent = hwnd(";winHandle$;")"
       end if
       print #code, "    hTip=CreateTooltip(hParent)"
       print #code, ""
       print #code, "    '----Add tooltips for controls"
       print #code, ""
    end if
    if ttC=1 then
        print #code, "    if VERSION.FLAG = 0 then"
        for idx = 1 to objectCount
            if tooltip$(idx) <> "" then
                tooltipCount = tooltipCount + 1
                t$=winHandle$+"."+names$(idx)
                print #code, "        Call AddToolTip Hwnd(";t$;") ,";_
                " hTip , ";chr$(34);tooltip$(idx);chr$(34)
            end if
        next idx
        if tooltipCount > 0 then print #code, "    end if"
        if tooltipCount > 0 then print #code, ""
        if tooltipCount > 0 then print #code, "    '----End tooltip code"
    end if
    if produceOutline = 0 then [doneProducingCode]

[produceOutline] ' produce outline code if flag is set
    inputLoopLabel$ = "[" + mid$(winHandle$, 2) + ".inputLoop]"
    print #code, ""
    print #code, ""
    print #code, inputLoopLabel$; "   'wait here for input event"
    print #code, "    wait"
    print #code, ""
    branchLabels$ = ""
    if objectCount < 2 then [outlineForMenus]
    for x = 2 to objectCount
        if left$(branchLabel$(x),2)<>"[]" then
            if left$(trim$(branchLabel$(x)), 1) <> "[" then [nextOutlineObject]
            if instr(trim$(branchLabel$(x)), " ") > 0 then gosub [handleMultiBranchLabels] : goto [nextOutlineObject]
            if instr(branchLabels$, branchLabel$(x)) > 0 then [nextOutlineObject]

'check for multiple access
        dont=0
        for multiAccess= 1 to x-1
            if branchLabel$(multiAccess)=branchLabel$(x) or branchLabel$(x)="[quit]"then dont=1
        next multiAccess
        if dont=1 then [nextOutlineObject]
        branchLabels$ = branchLabels$ + " " +branchLabel$(x)
        print #code, ""
        print #code, ""
        print #code, branchLabel$(x); "   'Perform action for the "; type$(x); " named '"; names$(x); "'"
'------------------------------------------------------
'------------ add control import code here ------------
'------------------------------------------------------
       if trim$(incFile$(x))<>"" then
           print #code, ""
           if fileExists(path$,incFile$(x)) then
               print #code, "'    Code imported from ";incFile$(x)
               open incFile$(x) for input as #fromFile
               inc$ = Input$(#fromFile, lof(#fromFile))
                        print #code, inc$
               close #fromFile
            else
                print #code, "    'Could not locate ";incFile$(x)
                print #code, "    'Insert your own code here"
                print #code, ""
            end if
        else
            print #code, ""
            print #code, "    'Insert your own code here"
            print #code, ""
        end if
        print #code, "    wait"
      end if
[nextOutlineObject]
    next x

[outlineForMenus]   'produce outline code for menus
    if menuCount = 0 then [doneProducingCode]
    for x = 1 to menuCount '-1
        if menuItemCount(x) = 0 then [writeNextMenu]
        for y = 0 to menuItemCount(x)-1
            brk=0
            mi$ = menuItem$(x, y)
             a=instr(mi$,chr$(0))+1
             l=len(mi$)
             for brl=a to l ' while mid$(mi$,l,1)<>chr$(0)
             if mid$(mi$,brl,1)=chr$(0))then brk=brl
             next brl
             bmi$=right$(mi$,l-brk)
             mi$=left$(mi$,brk-1)
             include=0
             if trim$(bmi$)="n/a" then bmi$=""
            if trim$(bmi$)<>""  then include=1
            if right$(mi$,1) = "|"  then [writeNextMenuItem]
            bl$ = mid$(mi$, instr(mi$, chr$(0)) + 1)
            if  bl$ = "[quit]" then [writeNextMenuItem]
            dont=0
            for multiAccess= 2 to objectCount
            if branchLabel$(multiAccess)=bl$  then dont=1
            if  bl$ = "[quit]" then dont=1
            next multiAccess
            if dont=1 then [writeNextMenuItem]
            if instr(branchLabels$, bl$) > 0 then [writeNextMenuItem]
            branchLabels$ = branchLabels$ + " " + bl$
            print #code, ""
            print #code, ""
            print #code, bl$; "   'Perform action for menu "; menu$(x); ", item "; left$(mi$, instr(mi$, chr$(0)) - 1)
            print #code, ""
            if include=1 then
                if fileExists(path$,bmi$) then
                    print #code, "'    Code imported from ";bmi$
                    open bmi$ for input as #fromFile
                        inc$ = Input$(#fromFile, lof(#fromFile))
                        print #code, inc$
                    close #fromFile
                 else
                     print #code, "    'Could not locate ";bmi$
                     print #code, "    'Insert your own code here"
                     print #code, ""
                 end if
             else
                 print #code, "    'Insert your own code here"
                 print #code, ""
             end if
             print #code, "    wait"
[writeNextMenuItem]
        next y
[writeNextMenu]
    next x
[doneProducingCode] ' Code creation complete
    if makeStatusbar = 1  then
        print #code, ""
        print #code, "[changeMessageBar]"
        print #code, "    '----This changes the text in the statusbar"
        print #code, "    '----Change the text in value$ then gosub this routine"
        print #code, "    value$=";chr$(34);"New Text";chr$(34)
        print #code, "    a= SendMessagePtr(hStatusBar,_WM_SETTEXT,0,value$)"
        print #code, "    wait"
        print #code, ""
        if instr(windowType$,"window",0) > 0 and _
            instr(windowType$,"_nf",0) = 0  then
            print #code, ""
            print #code, ""
            print #code, "[resizeStatusbar]"
            print #code, "    '----This makes the statusbar fit when window is resized"
            print #code, "    a= SendMessageLong(hStatusBar,_WM_SIZE,0,WindowWidth)"
            print #code, "    wait"
            print #code, ""
            print #code, "    '----End of statusbar resizer code"
        end if
        print #code, ""
    end if
    if produceOutline = 1 then
        print #code, ""
        print #code, "[quit.";mid$(winHandle$, 2);"] 'End the program"
        if makeStatusbar = 1  then
            print #code, ""
            print #code, "    a= SendMessageLong(hStatusBar,_WM_DESTROY,0,0) 'Destroy the statusbar"
        end if
        if makeTooltips = 1 and ttC=1 then
        print #code, ""
        print #code, "    a= ReleaseTooltipMemory(hTip)"
        end if
        print #code, "    close ";winHandle$
        print #code, "    end"
        if makeStatusbar = 1 = 1 or ttC = 1 then
        print #code, " "
        print #code, " "
        print #code, "'------------------------------------------------------"
        print #code, "'----------------- Subs and Functions -----------------"
        print #code, "'------------------------------------------------------"
        print #code, ""
        end if
'Create statusbar functions
        if makeStatusbar = 1 then
        print #code, "FUNCTION initalizeStatusBar(h, value$)"
        print #code, ""
        print #code, "    calldll #comctl32,";chr$(34);"InitCommonControls";chr$(34);",_"
        print #code, "    result as long"
        print #code, ""
        print #code, "    styleValue = _WS_VISIBLE or _WS_CHILD"
        print #code, "    calldll #comctl32,";chr$(34);"CreateStatusWindow";chr$(34);",_"
        print #code, "    styleValue as long,_"
        print #code, "    value$ as ptr,_"
        print #code, "    h as long,_"
        print #code, "    22 as long,_"
        print #code, "    r as long"
        print #code, "    initalizeStatusBar=r"
        print #code, "END FUNCTION"
        print #code, ""
        print #code, ""
        print #code, "FUNCTION SendMessagePtr(hWnd,msg,w,p$)"
        print #code, "    CallDLL #user32, ";chr$(34);"SendMessageA";chr$(34);",_"
        print #code, "    hWnd As long, _"
        print #code, "    msg As long,_"
        print #code, "    w As long,_"
        print #code, "    p$ As ptr,_"
        print #code, "    SendMessagePtr As long"
        print #code, "END FUNCTION"
        print #code, ""
        print #code, ""
        print #code, "FUNCTION SendMessageLong(hStatusBar,msg,w,p)"
        print #code, "    CallDLL #user32, ";chr$(34);"SendMessageA";chr$(34);",_"
        print #code, "    hStatusBar As long, _"
        print #code, "    msg As long,_"
        print #code, "    w As long,_"
        print #code, "    p As long,_"
        print #code, "    SendMessagePtr As long"
        print #code, "END FUNCTION"
        print #code, ""
         end if
'create tooltip functions
        if ttC = 1 then
        print #code, ""
        print #code, "FUNCTION CreateTooltip(hMain)"
        print #code, "    Struct TOOLINFO, _"
        print #code, "    cbSize As long, _"
        print #code, "    uFlags As long, _"
        print #code, "    hwnd As long, _"
        print #code, "    uId As long, _"
        print #code, "    rectLeft As long, _"
        print #code, "    rectTop As long, _"
        print #code, "    rectRight As long, _"
        print #code, "    rectBottom As long, _"
        print #code, "    hinst As long, _"
        print #code, "    lpszText As ptr"
        print #code, ""
        print #code, "    CallDLL #comctl32,";chr$(34);"InitCommonControlsEx";chr$(34);", _"
        print #code, "    ret As void"
        print #code, ""
        print #code, "    TOOLINFO.cbSize.struct = Len(TOOLINFO.struct)"
        print #code, "    TOOLINFO.uFlags.struct = flags Or 17 'TTF_IDISHWND Or TTF_SUBCLASS"
        print #code, "    TOOLINFO.hwnd.struct = hMain"
        print #code, ""
        print #code, "    CallDLL #user32,";chr$(34);"CreateWindowExA";chr$(34);",_"
        print #code, "    0 As long, _"
        print #code, "    ";chr$(34);"tooltips_class32";chr$(34);" As ptr, _"
        print #code, "    0 As long, style As long, _"
        print #code, "    _CW_USEDEFAULT As long, _"
        print #code, "    _CW_USEDEFAULT As long, _"
        print #code, "    _CW_USEDEFAULT As long, _"
        print #code, "    _CW_USEDEFAULT As long, _"
        print #code, "    hMain As long, _"
        print #code, "    0 As long, _"
        print #code, "    0 as long, _"
        print #code, "    0 As long, _"
        print #code, "    CreateTooltip As Long"
        print #code, "END FUNCTION"
        print #code, ""
        print #code, ""
        print #code, "SUB AddToolTip cHndl, hWnd, Text$"
        print #code, ""
        print #code, "    TOOLINFO.uId.struct = cHndl"
        print #code, "    TOOLINFO.lpszText.struct = Text$"
        print #code, ""
        print #code, "    CallDLL #user32, ";chr$(34);"SendMessageA";chr$(34);",_"
        print #code, "    hWnd As long, _"
        print #code, "    1028 As long, _"
        print #code, "    0 As long, _"
        print #code, "    TOOLINFO as ptr, _"
        print #code, "    ret As long"
        print #code, "END SUB"
        print #code, ""
        print #code, ""
        print #code, "FUNCTION ReleaseTooltipMemory(hTip)"
        print #code, "    CallDLL #user32, ";chr$(34);"SendMessageA";chr$(34);",_"
        print #code, "    hTip As long, _"
        print #code, "    _WM_DESTROY  As long, _"
        print #code, "    w As long, _"
        print #code, "    l As long, _"
        print #code, "    re As long"
        print #code, "END FUNCTION"
        print #code, ""
        end if
        if makeStatusbar = 1 or ttC = 1 then
        print #code, ""
        print #code, "'------------------------------------------------------"
        print #code, "'--------------- End Subs and Functions ---------------"
        print #code, "'------------------------------------------------------"
        end if
    end if
    produceOutline = 0
    print #code, "!selectall";
    print #code, "!copy";
    print #code, "!origin 1 1";
    timer 100,[testHandle]
    if testCode = 0 then
        notice "Done.  This code has been copied to clipboard.  You may paste it into your program."
     else
        testCode = 0
        goto [testRun]
    end if
    wait

[handleMultiBranchLabels]   'handle the case where a control has more than 1 branching option
    if word$(branchLabel$(x), 1)="[quit]" then [nextMultiBranchLabel]
    if instr(branchLabels$, word$(branchLabel$(x), 1)) > 0 then [nextMultiBranchLabel]
    print #code, ""
    print #code, word$(branchLabel$(x), 1); "   'Perform action for the "; type$(x); " named '"; names$(x); "'"
    print #code, ""
'-----------------------
       if trim$(incFile$(x))<>"" then
           print #code, ""
           if fileExists(path$,incFile$(x)) then
               print #code, "'    Code imported from ";incFile$(x)
               open incFile$(x) for input as #fromFile
               inc$ = Input$(#fromFile, lof(#fromFile))
                        print #code, inc$
               close #fromFile
            else
                print #code, "    'Could not locate ";incFile$(x)
                print #code, "    'Insert your own code here"
                print #code, ""
            end if
        else
      print #code, ""
    print #code, "    'Insert your own code here"
    print #code, ""
end if
    print #code, "    wait"
    branchLabels$ = branchLabels$ + " " + word$(branchLabel$(x), 1)
[nextMultiBranchLabel]
    if word$(branchLabel$(x), 2)="[quit]" then [doneMultiBranchLabel]
    print #code, ""
    if instr(branchLabels$, word$(branchLabel$(x), 2)) > 0 then [doneMultiBranchLabel]
    print #code, ""
    print #code, ""
    print #code, word$(branchLabel$(x), 2); "   'Perform action for the "; type$(x); " named '"; names$(x); "'"
    print #code, ""
    print #code, "    'Insert your own code here"
    print #code, ""
    print #code, "    wait"
    branchLabels$ = branchLabels$ + " " + word$(branchLabel$(x), 2)
[doneMultiBranchLabel]
    return

[filePath] ' Extract file path from complete file specification
    length = len(bmpFileName$)
    character = length
    slash$ = ""
    while slash$ <> "\"
        slash$ = mid$(bmpFileName$,character,1)
        character = character - 1
    wend
    pathName$ = left$(bmpFileName$,character-1)
    return

[codeForTextEditColor]
    if boxcolor$(x)<> holdTextEditColor$ then
        holdTextEditColor$=boxcolor$(x)
        colorcode$ = "    TexteditorColor$ = "+qu$+boxcolor$(x)+qu$
    end if
    return

[codeForComboBoxColor]
    if boxcolor$(x)<> holdComboBoxcolor$ then
        holdComboBoxcolor$=boxcolor$(x)
        colorcode$ = "    ComboboxColor$ = "+qu$+boxcolor$(x)+qu$
    end if
    return

[codeForTextBoxColor]
    if boxcolor$(x)<> holdTextBoxColor$ then
      '  if trim$(boxcolor$(x))="" then boxcolor$(x)="white"
        holdTextBoxColor$=boxcolor$(x)
        colorcode$ = "    TextboxColor$ = "+qu$+boxcolor$(x)+qu$
    end if
    return

[codeForListBoxColor]
    if boxcolor$(x)<> holdListboxColor$ then
        holdListboxColor$=boxcolor$(x)
        colorcode$ = "    ListboxColor$ = "+qu$+boxcolor$(x)+qu$
    end if
    return

[codeForBmpButton] 'produce code for a bmp button
    bmpFileName$ = bmpFileName$(x)
    if bmpPath$ <> "" then gosub [fileName]:bmpFileName$ = fileName$
    blc$=checkQuit$(branchLabel$(x),x,winHandle$)
    code$ = "    bmpbutton "+winHandle$+"."+names$(x)+", "+qu$+bmpPath$+bmpFileName$+qu$+", "+blc$+", "+corner$(x)+", "+str$(xOrg(x)-xOrg-4)+", "+str$(yOrg(x)-yOrg-20-4)
    return

[fileName] ' Extract file name from complete file specification
    length = len(bmpFileName$)
    character = length
    slash$ = ""
    while slash$ <> "\"
        slash$ = mid$(bmpFileName$,character,1)
        character = character - 1
    wend
    fileName$ = right$(bmpFileName$,length-character-1)
    return

[codeForButton] 'produce code for a text button
    gosub [columnizeSpecs]
    blc$=checkQuit$(branchLabel$(x),x,winHandle$)
    code$ =  "    "+type$(x)+" "+winHandle$+"."+names$(x)+","+qu$+label$(x)+qu$+","+blc$+", "+corner$(x)+","+xX$+","+yY$+","+wW$+","+hH$
    return

[codeForType1]'produce code for a textbox, texteditor, or graphic box
    gosub [columnizeSpecs]
    tType$=type$(x)
    if type$(x)="textedit" then tType$="texteditor"
    code$ = "    "+tType$+" "+winHandle$+"."+names$(x)+","+xX$+","+yY$+","+wW$+","+hH$
   return

[codeForType2] 'produce code for statictext and groupbox
    gosub [columnizeSpecs]
    code$ = "    "+type$(x)+" "+winHandle$+"."+names$(x)+", "+qu$+label$(x)+qu$+","+xX$+","+yY$+","+wW$+","+hH$
    return

[codeForType3] 'produce code for listbox and combobox
    gosub [columnizeSpecs]
    blc$=checkQuit$(branchLabel$(x),x,winHandle$)
    code$ = "    "+type$(x)+" "+winHandle$+"."+names$(x)+", "+arrayName$(x)+", "+blc$+", "+xX$+","+yY$+","+wW$+","+hH$
    return

[codeForType4] 'produce code for radiobutton and checkbox
    gosub [columnizeSpecs]
    blc1$=checkQuit$(word$(branchLabel$(x), 1),x,winHandle$)
    blc2$=checkQuit$(word$(branchLabel$(x), 2),x,winHandle$)
    code$ = "    "+type$(x)+" "+winHandle$+"."+names$(x)+", "+qu$+label$(x)+qu$+", "+blc1$+", "+blc2$+","+xX$+","+yY$+","+wW$+","+hH$
    return

[columnizeSpecs]
    xX$=str$(xOrg(x)-xOrg-4)
    yY$=str$(yOrg(x)-yOrg-20-4)
    wW$=str$(width(x))
    hH$=str$(height(x))
    while len(xX$)<4:xX$=" "+xX$:wend
    while len(yY$)<4:yY$=" "+yY$:wend
    while len(wW$)<4:wW$=" "+wW$:wend
    while len(hH$)<4:hH$=" "+hH$:wend
RETURN

[newFile] 'clear the contents of the form editor and start over
    cancelOpp=0
    includeCode=0
    if objectCount <2 and menuCount > 0 then gosub [menuSaveErr]
    if cancelOpp=1 then cancelOpp=0: wait
    if isModified = 1 then gosub [formIsModified]
    if cancelOpp=1 then wait
    gosub [defineVariables]
    gosub [changeMenuText]
    redim tooltip$(100)
    redim controlFont$(100)
    gosub [clearMenuData]
    gosub [addWindowFrame]
    gosub [renderWindow]'[drawTheWindow]
    gosub [redrawAll]
    isModified = 0
    print #form, "setfocus";
    wait
[auxSave]
    if formName$="untitled.ffa" and isModified = 0 then wait
    fname$=fileSpec$(formName$,0)    ' 0=File name  1=File path
    saveTitle$="Save ";fname$;" as"
    filedialog saveTitle$,  "*.ffa",newFormName$
    if newFormName$= "" then [inputLoop]
    newFormName$=fixExtension$(newFormName$)
    if newFormName$<>".ffa" then formName$=newFormName$
return

[saveFile] ' Save the form to a file
    'save the form into a *.ffa file, future can be ffb or ffc, etc.
    if objectCount <2 then
        notice "Oops..."+chr$(13)+_
               "Freeform 3 can not save a form that has no controls."
        wait
    end if
    if isModified = 0 then wait
    if formName$="untitled.ffa" then goto [saveFileAs]
    if formName$<>"" then gosub [saveFormSubroutine]
        wait

[saveFileAs] ' Save the form to a file
   if objectCount <2 then
        notice "Oops..."+chr$(13)+_
               "Freeform3 can not save a form that has no controls."
        wait
    end if
    if formName$="untitled.ffa" and isModified = 0 then wait
    fname$=fileSpec$(formName$,0)    ' 0=File name  1=File path
    saveTitle$="Save ";fname$;" as"
    filedialog saveTitle$,saveTemplate$,newFormName$
    if newFormName$= "" then [inputLoop]
    newFormName$=fixExtension$(newFormName$)
    if newFormName$<>".ffa" then formName$=newFormName$
    if fileExists(fileSpec$(formName$,1),fileSpec$(formName$,0)) then
        confirm formName$+ "alreade exists."+chr$(13)+_
        "Do you want to overwrite it?";conf$
       if conf$<>"yes" then   print #form, "setfocus":wait
    end if
    gosub [saveFormSubroutine]
    newTitle$=title$+" - "+fileSpec$(newFormName$,0)
    call changeTitleBar hParent,  newTitle$ 
    print #form, "setfocus";
    isModified = 0
    wait

[saveFormSubroutine]   'the subroutine portion of the save routine
    isModified = 0
    if right$(formName$,4)<>".ffa" then formName$=formName$+".ffa"
    open formName$ for output as #formOut
    print #formOut, currentForegroundColor$
    print #formOut, currentBackgroundColor$
    print #formOut, newControlNumber
    print #formOut, windowLabel$
    print #formOut, windowType$
    print #formOut, objectCount
    print #formOut, winHandle$
    print #formOut, snapOn
    print #formOut, xInterval
    print #formOut, yInterval
    print #formOut, menuCount
    print #formOut, windowXExtent
    print #formOut, windowYExtent
    print #formOut, windowComboboxColor$
    print #formOut, windowListboxColor$
    print #formOut, windowTextboxColor$
    print #formOut, windowTexteditorColor$
    print #formOut, windowUpperLeftX
    print #formOut, windowUpperLeftY
    print #formOut, bmpPath$
    print #formOut, font$(1)
    print #formOut, bmpCount
    print #formOut, makeTooltips
    print #formOut, makeStatusbar
    if objectCount = 1 then
        print #formOut, type$(i)
        print #formOut, label$(i)
        print #formOut, names$(i)
        print #formOut, xOrg(i)
        print #formOut, yOrg(i)
        print #formOut, width(i)
        print #formOut, height(i)
        print #formOut, corner$(i)
        print #formOut, branchLabel$(i)
        print #formOut, segment(i)
        print #formOut, handle$(i)
        print #formOut, bmpName$(i)
        print #formOut, bmpFileName$(i)
        print #formOut, arrayName$(i)
        print #formOut, tooltip$(i)
        print #formOut, boxcolor$(i)
    else
    for i = 2 to objectCount
        print #formOut, type$(i)
        print #formOut, label$(i)
        print #formOut, names$(i)
        print #formOut, xOrg(i)
        print #formOut, yOrg(i)
        print #formOut, width(i)
        print #formOut, height(i)
        print #formOut, corner$(i)
        print #formOut, branchLabel$(i)
        print #formOut, segment(i)
        print #formOut, handle$(i)
        print #formOut, bmpName$(i)
        print #formOut, bmpFileName$(i)
        print #formOut, arrayName$(i)
        print #formOut, tooltip$(i)
        print #formOut, boxcolor$(i)
        if controlFont$(i)="" then controlFont$(i)=font$(1)
        print #formOut, controlFont$(i)
        print #formOut, incFile$(i)
    next i
    for i=1 to 25
        print #formOut, " " 'Dummy lines that can be used in the future
    next i                  'without re-writing everything.
    end if
    'Now write the menu information
    if menuCount = 0 then [noMenusToSave]
    for i = 1 to menuCount  '-1
        print #formOut, menu$(i)
        print #formOut, menuItemCount(i)
        if menuItemCount(i) = 0 then [noMenuItemsToSave]
        for j = 0 to menuItemCount(i)-1
            print #formOut, menuItem$(i, j)
        next j
      [noMenuItemsToSave]
    next i

[noMenusToSave]
    close #formOut
    notice formName$+" has been saved."
    return

[openFile] 'load the form from a *.ffa,*.fr3 file
    cancelOpp=0
    if objectCount <2 and menuCount > 0 then gosub [menuSaveErr]
    if isModified = 1 then gosub [formIsModified]
    if cancelOpp=1 then wait
    File$=lastPath$+"\"+openTemplate$

    filedialog "Open form",File$,newFormName$
    print #form, "setfocus"
    if newFormName$ = "" then [inputLoop]
    test$=right$(newFormName$,3)
    if instr(openTemplate$,test$)= 0 then
        notice"Problem"+chr$(13)+"Freeform does not recognize ";test$;" type files."
        wait
    end if


    formName$=newFormName$
    lastPath$=fileSpec$(newFormName$,1)
    gosub [clearMenuData]
    objectCount = 0
    textEditControl=0
    gosub [addWindowFrame]
    open formName$ for input as #formIn
    line input #formIn, currentForegroundColor$
    line input #formIn, currentBackgroundColor$
    line input #formIn, newControlNumber
    line input #formIn, windowLabel$
    line input #formIn, windowType$
    line input #formIn, objectCount
    line input #formIn, winHandle$
    line input #formIn, snapOn
    line input #formIn, xInterval
    line input #formIn, yInterval
    line input #formIn, menuCount
    line input #formIn, windowXExtent
    line input #formIn, windowYExtent
    line input #formIn, windowComboboxColor$
    line input #formIn, windowListboxColor$
    line input #formIn, windowTextboxColor$
    line input #formIn, windowTexteditorColor$
    line input #formIn, windowUpperLeftX
    line input #formIn, windowUpperLeftY
    line input #formIn, bmpPath$
    line input #formIn, fontChosen$:font$(1)=fontChosen$ 
    line input #formIn, bmpCount
    line input #formIn, makeTooltips
    line input #formIn, makeStatusbar
    width(1) = windowXExtent
    height(1) = windowYExtent
    xInterval(1)=xInterval
    yInterval(1)=yInterval

    wincolor$ = currentBackgroundColor$
    if objectCount > 1 then
        for i = 2 to objectCount
            line input #formIn,type$(i)
            line input #formIn,label$(i)
            line input #formIn,names$(i)
            line input #formIn,xOrg(i)
            line input #formIn,yOrg(i)
            line input #formIn,width(i)
            line input #formIn,height(i)
            line input #formIn,corner$(i)
            line input #formIn,branchLabel$(i)
            line input #formIn,segment(i)
            line input #formIn,handle$(i)
            line input #formIn,bmpName$(i)
            line input #formIn,bmpFileName$(i)
            if trim$(bmpFileName$(i)) > "" then loadbmp bmpName$(i), bmpFileName$(i)
            line input #formIn,arrayName$(i)
            line input #formIn,tooltip$(i)
            line input #formIn,boxcolor$(i)
            if right$(newFormName$,3)=right$(saveTemplate$,3) then _
                line input #formIn, controlFont$(i)
            if controlFont$(i)="" then controlFont$(i)=font$(1)
            if test$="ffa" then
               line input #formIn, incFile$(i)
            else
               incFile$(i)=""
            end if
        next i

        if right$(newFormName$,3)=right$(saveTemplate$,3) then
            for i=1 to 25
                line input #formIn,dmy$ 'Dummy lines that can be used in the future
            next i                      'without re-writing everything.
        end if

'        if right$(newFormName$,3)=right$(saveTemplate$,3) then
'            for i=1 to 24
'                line input #formIn,dmy$ 'Dummy lines that can be used in the future
'            next i                      'without re-writing everything.
'        end if

        for qq = 1 to objectCount
            if bmpName$(qq)<>"" and bmpFileName$(qq)<>"" then
                loadbmp bmpName$(qq),bmpFileName$(qq)
            end if
        next qq
    end if

    if menuCount = 0 then [noMenusToRead]
    for i = 1 to menuCount  '-1
        line input #formIn, tmp$ : menu$(i)=tmp$
        line input #formIn, tmp : menuItemCount(i) = tmp
        if menuItemCount(i) = 0 then [noMenuItemsToRead]
        for j = 0 to menuItemCount(i)-1
            line input #formIn, tmp$ : menuItem$(i, j) = tmp$
            if test$="fr3" then  menuItem$(i, j) =menuItem$(i, j)+chr$(0)+"n/a"
        next j
      [noMenuItemsToRead]
    next i

[noMenusToRead]
    close #formIn
    gosub [redrawAll]
    toolTipControl=1
    wC=0
    gosub [changeMenuText]
    isModified = 0
    print #form, "setfocus"

    if test$<>"ffa" then
        newFormName$=left$(newFormName$,len(newFormName$)-3)+"ffa"
        formName$=newFormName$
        isModified = 1
    end if
    newTitle$=title$+" - "+fileSpec$(newFormName$,0)
    call changeTitleBar hParent,  newTitle$ 
    wait

[gridDialog]  'open a dialog box for selecting & adjusting snap to grid
    WindowWidth = 220
    WindowHeight = 255
    UpperLeftX = DisplayWidth/2 - 250/2
    UpperLeftY = DisplayHeight/2 - 270/2
    if gridDialogIsOpen = 1 then close #gridDialog
    groupbox #gridDialog.gr1,"",5,1,205,190
    statictext #gridDialog.statictext2, "Select here whether control positions will", 10, 16, 336, 20
    statictext #gridDialog.statictext5, "automatically snap to gridded positions,", 10, 35, 320, 20
    statictext #gridDialog.statictext6, "and what the interval will be.", 10, 54, 240, 20
    checkbox #gridDialog.snapOnOff, " &Snap to Grid", [snapOn], [snapOff], 34, 85, 120, 20
    checkbox #gridDialog.viewGrid, " &Visible Grid", [gridVisibleOn], [gridVisibleOff], 34, 110, 120, 20
    statictext #gridDialog.statictext7, "X interval:", 34, 135, 70, 20
    textbox #gridDialog.xIntrvl, 34, 160, 38, 23
    statictext #gridDialog.statictext9, "Y interval:", 124, 135, 70, 20
    textbox #gridDialog.yIntrvl, 124, 160, 38, 23
    button #gridDialog, "&OK", [acceptGridDialog],    UL, 55,198, 75, 23
    button #gridDialog, "&Cancel", [cancelGridDialog],UL,133,198, 75, 23
    open "Snap to Grid" for dialog_modal as #gridDialog
    print #gridDialog, "trapclose [cancelGridDialog]"
    gridDialogIsOpen = 1
    if snapOn = 1 then snapOnSelected = 1 : print #gridDialog.snapOnOff, "set"
    if gridVisibleOn = 1 then gridVisibleSelected = 1 : print #gridDialog.viewGrid, "set"
    print #gridDialog.xIntrvl, xInterval
    print #gridDialog.yIntrvl, yInterval
    wait


[snapOn]   'Perform on action for the checkbox named 'snapOnOff'
    snapOnSelected = 1
    wait

[snapOff]   'Perform off action for the checkbox named 'snapOnOff'
    snapOnSelected = 0
    wait

[gridVisibleOn] ' Turn on grid flag
    gridVisibleSelected = 1
    wait

[gridVisibleOff] ' Turn off grid flag
    gridVisibleSelected = 0
    wait

[acceptGridDialog]
    snapOn = snapOnSelected
    gridVisibleOn = gridVisibleSelected
    print #gridDialog.xIntrvl, "!contents? xInterval"
    print #gridDialog.yIntrvl, "!contents? yInterval"
    settingsChanged = 1
   xInterval(1)=xInterval
   yInterval(1)=yInterval

[cancelGridDialog]
    gridDialogIsOpen = 0
    close #gridDialog
    if settingsChanged = 1 then settingsChanged = 0 : gosub [redrawAll]
    wait

[editMenus]
    gosub [deselectOnly]
    gosub [checkPosition]
'Reworked by Stephen Rose
    dim menuItemHold$(30)
    dim menuHold$(100)
    menuIsChanged=0
    menuItemIndex = 0
    result = 0
    if editMenuIsOpen = 1 then close #editMenu
    editMenuIsOpen = 1
    WindowWidth = 387 : WindowHeight =387' 402 '422
    UpperLeftX  = 125 : UpperLeftY   =  60
    groupbox #editMenu.gr1,"",-1,-5,381,190
    groupbox #editMenu.gr2,"",-1,-5,381,362
    ListboxColor$="white"
    Listbox     #editMenu.menuList, menu$(, [selectMenuToEdit], 5, 30, 270, 145
    Listbox     #editMenu.menuItems, menuItemLocal$(, [selectMenuItem], 5, 205, 270, 145
    Statictext  #editMenu.static1, "Available Menus:", 5,15, 105, 15
    Statictext  #editMenu.static2, "Menu Items -> Branch Labels:", 5, 190, 195, 15
    Button      #editMenu.close, "&Close",[closeMenuEdit],UL, 280, 5, 90, 22
    Button #editMenu.AddMenu,"&New Menu",[addAMenu],UL, 280, 30,90, 25
    Button #editMenu.RemoveMenu,"&Remove Menu",[deleteMenu],UL,280, 60, 90, 25
    Button #editMenu.MoveUpMenu,"Ý",[moveMenuUp],         UL,280,120,90, 25
    Button #editMenu.MoveDownMenu,"ß",[moveMenuDown],     UL,280,150,90, 25
    Button #editMenu.EditMenu,"&Edit Menu",[editThisMenu],UL,280, 90,90, 25
    Button #editMenu.NewItem,"Ne&w Item",[addNewMenuItem],UL,280,205,90, 25
    Button #editMenu.RemoveItem,"Re&move Item",[deleteMenuItem],UL,280,235,90, 25
    Button #editMenu.EditItem,"E&dit Item",[editMenuItem],UL,280,265,90, 25
    Button #editMenu.MoveUpItem,"Ý",[moveMenuItemUp],     UL,280,295,90, 25
    Button #editMenu.MoveDownItem,"ß",[moveMenuItemDown], UL,280,325,90, 25
    Open "Menu Editor" For dialog_modal As #editMenu
    Print #editMenu, "trapclose [closeMenuEdit]"
    print #editMenu.menuList, "singleclickselect";
    print #editMenu.menuItems, "singleclickselect";
    print #editMenu.menuList, "selectIndex 1"
    print #editMenu.MoveUpItem,"!font symbol 12"
    print #editMenu.MoveDownItem,"!font symbol 12"
    print #editMenu.MoveUpMenu,"!font symbol 12"
    print #editMenu.MoveDownMenu,"!font symbol 12"
    if menuCount then goto [selectMenuToEdit]
[menu.inputLoop]
    wait

[deleteMenu]   'remove a menu from the list of menus
    print #editMenu.menuList, "selectionIndex? result"
    print #editMenu.menuList, "selection? result$"
    if result$ = "Edit" then
        needEdit = 0
        for x = 1 to objectCount
        if type$(x) = "textedit" then needEdit = 1
        next x
        if needEdit = 1 then notice "Sorry"+chr$(13)+"You can not Delete the Edit menu because you have a texteditor and Liberty BASIC automaticly adds a Edit menu to the form if you do.":wait
    end if
    if result then
        for x = result to menuCount
            menu$(x) = menu$(x+1)
            menuItemCount(x)=menuItemCount(x+1)
        next x
        for y = result to menuCount
            for x = 0 to 29
                menuItem$(y,x) = menuItem$(y+1,x)
            next x
        next y
        for x = 0 to 29
            menuItem$(result+1, x) = ""
        next x
        dim menuItemLocal$(30)
        print #editMenu.menuItems, "reload"
        print #editMenu.menuList,"reload"
        result = result - 1
        menuCount = menuCount - 1
        if result = 0 then result = 1
        print #editMenu.menuList, "selectIndex ";result
        menuIsChanged=1
    end if
    wait

[selectMenuToEdit]   'populate the listbox named menuItems
    print #editMenu.menuList, "selectionIndex?"
    input #editMenu.menuList, result
    if result = 0 or result > menuCount+1 then wait
    for x = 0 to 29
        mil$ = menuItem$(result, x)
        if mil$ <> "" then mil$ = left$(mil$, instr(mil$, chr$(0)) - 1) + " -> " + mid$(mil$, instr(mil$, chr$(0)) + 1)
        menuItemLocal$(x) = mil$
    next x
    print #editMenu.menuItems, "reload"
    menuItemIndex = 0
wait

[deleteMenuItem]   'Perform action for the button named 'deleteMenuItem'
    print #editMenu.menuList, "selectionIndex? result"
    print #editMenu.menuItems, "selectionIndex? menuItemIndex"
    if result = 0 or menuItemIndex=0 or menuItemCount(result) = 0 then wait
    r=menuItemIndex
    rr=result
    menuItemCount(result) = menuItemCount(result)-1
    for x = menuItemIndex to 30
        menuItem$(result,x-1) = menuItem$(result,x)
        menuItem$(result, x)=""
    next x
    gosub [reloadLocalMenuItems]
    if r < menuItemCount(rr-1)+1 then
    print #editMenu.menuItems, "selectIndex ";r
    else
    print #editMenu.menuItems, "selectIndex ";r-1
    end if
    menuItemIndex = 0
wait

[reloadLocalMenuItems]  'reload the contents of the menu items listbox
    for x = 0 to 29
        mil$ = menuItem$(result, x)
        if trim$(mil$) <> "" then mil$ = left$(mil$, instr(mil$, chr$(0)) - 1) + " -> " + mid$(mil$, instr(mil$, chr$(0)) + 1)
        menuItemLocal$(x) = mil$
    next x
    print #editMenu.menuItems, "reload"
return

[MenuItemseperator.set]
    if seperator = 0 then
        print #menuItems.name,"!contents? holdItem$"
        print #menuItems.branchLabel,"!contents? holdBranch$"
    end if
    print #menuItems.name,space$(25);"n/a"
    print #menuItems.branchLabel,space$(25);"n/a"
    CallDLL #user32, "EnableWindow", item.name As long, 0 As boolean, r As boolean
    CallDLL #user32, "EnableWindow", item.branchLabel As long, 0 As boolean, r As boolean
    seperator = 1
    wait

[MenuItemseperator.reset]
    if seperator = 1 then
        print #menuItems.name,holdItem$
        print #menuItems.branchLabel,holdBranch$
    end if
    CallDLL #user32, "EnableWindow", item.name As long, 1 As boolean, r As boolean
    CallDLL #user32, "EnableWindow", item.branchLabel As long, 1 As boolean, r As boolean
    seperator = 0
    if editMenuItemAction$ = "ADD" then
        print #menuItems.name,"!contents? test$"
        if trim$(test$)="n/a" then
            print #menuItems.name,""
            print #menuItems.branchLabel,""
        end if
    else
        mi$ = menuItem$(result , menuItemIndex-1 )
        if left$(mi$,5)<>"-----"then
            print #menuItems.name, left$(mi$, instr(mi$, chr$(0)) - 1)
            print #menuItems.branchLabel, mid$(mi$, instr(mi$, chr$(0)) + 1)
        else
            print #menuItems.name,""
            print #menuItems.branchLabel,""
        end if
    end if
    print #menuItems.name, "!setfocus"
    wait

[acceptMenuItemAdd]   'Perform action for the button named 'acceptMenuItemProps'
    if editMenuItemAction$ = "ADD" then
        menuItemCount(result) =menuItemCount(result) + 1
        menuItemIndex = menuItemCount(result)
    end if
    print #menuItems.name, "!contents? nResult$"
    print #menuItems.branchLabel, "!contents? blResult$"
    blResult$=trim$(blResult$)
    If seperator then
       nResult$ ="--------------------------------------------------------------------------------------"
       blResult$ = "|"
    else
        if nResult$ = "" or _
        blResult$ = "" or_
        blResult$ = "[" or_
        blResult$ = "]" or_
        blResult$ = "[]" or_
        instr(blResult$," ")>0 then
            if instr(blResult$," ")>0 then
                notice "Spaces in branch Labels are not allowed."
                print #menuItems.branchLabel,"!setfocus"
            else
                if nResult$ = "" then
                    notice "Please enter menu item name to continue."
                    print #menuItems.name, "!setfocus"
                else
                    notice "Please enter branch label to continue."
                    print #menuItems.branchLabel,"!setfocus"
               end if
           end if
           menuItemCount(result) =menuItemCount(result)-1
           wait
       end if
       blr$ = trim$(blResult$)
       if left$(blr$, 1) <> "[" then blr$ = "[" + blr$
       if right$(blr$, 1) <> "]" then blr$ = blr$ + "]"
       blResult$=blr$
   end if
   print #menuItems.include,"!contents? incTest$"
   if trim$(incTest$)="" then includeFile$="n/a"
   if includeFile$="" then includeFile$="n/a"
   menuItem$(result, menuItemIndex - 1) = nResult$ + chr$(0) + blResult$+chr$(0)+includeFile$
   menuItemLocal$(menuItemIndex - 1) = nResult$ + " -> " + blResult$

   gosub [reloadLocalMenuItems]
   print #editMenu.menuItems, "reload"
   print #editMenu.menuItems, "selectIndex ";menuItemIndex
   r$=""
   if editMenuItemAction$ = "ADD" then print #menuItems.multi, "value? r$"
 incFile$=""
        includeFile$=""
        getInclude$=""

    if r$="set" then
        print #menuItems.xIt,"&Done"
        print #menuItems.name,""
        print #menuItems.branchLabel,""
        print #menuItems.include,""

        goto [keepItemsOpen]
    end if
    close #menuItems
wait

[selectMenuItem]
    print #editMenu.menuItems,"selectionindex? menuItemIndex"
wait

[addNewMenuItem]   'Perform action for the button named 'newItemButton'
    if result = 0 then wait
    editMenuItemAction$ = "ADD"
    editMenuTitleBar$="Add new menu item to "+menu$(result)
        includeFile$=""
        getInclude$=""
        incFile$=""


goto [editMenuItemProperties]


[editMenuItem]   'Perform action for the button named 'editMenuItem'
    print #editMenu.menuItems, "selectionIndex? menuItemIndex"
    if menuItemIndex = 0 then wait
    editMenuItemAction$ = "EDIT"
    mi$=menuItem$(result,menuItemIndex-1)
    sep$=mid$(mi$,instr(mi$, chr$(0)) + 1)
    if sep$<>"|" then
        editMenuTitleBar$="Edit "+menu$(result)+_
        " >> "+menuItem$(result, menuItemIndex-1)
    else
        editMenuTitleBar$="Edit "+menu$(result)+" >> "+"--seperator--"
    end if
'====================================
'break it down here
'====================================


[editMenuItemProperties]
    if result = 0 then wait
    WindowWidth = 340 : WindowHeight = 180
    UpperLeftX  = 1 : UpperLeftY   =  50
    groupbox #menuItems.gr1,"",-1,-6,334,157
    Statictext #menuItems.st1,"Menu Item name:", 10, 20, 105, 15
    Statictext #menuItems.st1,"Branch Label:",   10, 50, 85, 15
    Statictext #menuItems.st1,"Include file:",   10, 80, 85, 15
    TextBox #menuItems.name,       120, 15,207, 23
    Textbox #menuItems.branchLabel,120, 45,207, 23
    Textbox #menuItems.include,   120, 75,158, 23
    Button #menuItems.default,"&Accept",[acceptMenuItemAdd],UL,178,115, 75, 22
    Button #menuItems.xIt,"&Cancel",[cancelMenuItemEdit],   UL,252,115, 75, 22
    Button #menuItems.inc,"Import",[menuImport],            ul,278, 75, 48, 22
    am=110
    if editMenuItemAction$ = "ADD" then
    Checkbox    #menuItems.multi, " &Multiple Entries",[keepItemsOpen],[keepItemsOpen],10,105, 95, 16
    am=125
    end if
    Checkbox #menuItems.seperator, " &Separator",[MenuItemseperator.set],[MenuItemseperator.reset], 10, am, 85, 16
    Open editMenuTitleBar$ For dialog_modal As #menuItems
    Print #menuItems, "trapclose [cancelMenuItemEdit]"
    item.name = hwnd(#menuItems.name)
    item.branchLabel = hwnd(#menuItems.branchLabel)
    seperator = 0
    if editMenuItemAction$ = "ADD" then
    print #menuItems.name,""
        print #menuItems.branchLabel, ""
        print #menuItems.name, ""
        print #menuItems.branchLabel, ""
        print #menuItems.include, ""
        include$=""
   else
        if sep$<>"|" then
            print #menuItems.name, left$(mi$, instr(mi$, chr$(0)) - 1)
            print #menuItems.branchLabel, mid$(mi$, instr(mi$, chr$(0)) + 1)
        a=instr(mi$,chr$(0))+1
        l=len(mi$)
        for brl=a to l
            if mid$(mi$,brl,1)=chr$(0))then brk=brl
        next brl
        includeFile$=right$(mi$,l-brk)
        'mi$=left$(mi$,brk-1)

            if trim$(includeFile$)<>"" and includeFile$<>"n/a" then
                print #menuItems.include,fileSpec$(includeFile$,0)
            else
                print #menuItems.include,""
            end if
        else
        #menuItems.seperator,"set"
        goto [MenuItemseperator.set]
        end if
    end if
wait

[menuImport]
    incFile$=includeFile$
    if incFile$="n/a" then incFile$=""
    gosub [Include]
    includeFile$=getInclude$
    print #menuItems.include,fileSpec$(includeFile$,0)
wait
[keepItemsOpen]
    print #menuItems.name,"!setfocus"
    if seperator then
        holdItem$=""
        holdBranch$=""
        includeFile$=""
        getInclude$=""
        print #menuItems.seperator,"reset"
        goto [MenuItemseperator.reset]
    end if
wait

[cancelMenuItemEdit]
    close #menuItems
    wait

[editThisMenu]
    editMenuItemAction$ = "EDIT"
    addMenuTitle$="Edit Menu Title"
    goto [doAddaMenu]
[addAMenu]    'add a new menu item
    editMenuItemAction$ = "NEW"
    addMenuTitle$="Add a New Menu"
    if menuCount=20 then
    notice "The maximum menu limit has been reached."
    wait
    end if
[doAddaMenu]
    multiMenu=0
    WindowWidth = 330 : WindowHeight = 190
    UpperLeftX =1 : UpperLeftY =180
    groupbox #AddMenu.gr1,"",-2,-5,324,166
    Statictext  #AddMenu.statictext1, "Current Menus:", 5, 10, 90, 15
    Statictext  #AddMenu.statictext2, "Enter new menu name:", 180, 10, 135, 15
    Button      #AddMenu.default, "&Accept",[acceptNewMenu],UL, 214, 62, 105, 23
    Button      #AddMenu.exit, "&Cancel",[cancelNewMenu],UL, 214, 85, 105, 23
    Textbox     #AddMenu.newMenuName, 180, 25, 137, 24
    Listbox     #AddMenu.listbox, menu$(,[inputLoop], 5, 25, 170, 135
    if editMenuItemAction$<> "EDIT" then
    checkbox    #AddMenu.keepOpen," &Multiple Entries",[keepOpen],[keepOpen],195,125,125,25
    end if
    Open addMenuTitle$ For Dialog_modal As #AddMenu
    Print #AddMenu, "trapclose [cancelNewMenu]"
    Print #AddMenu, "font ms_sans_serif 8"
    if editMenuItemAction$ = "EDIT" then
    print #AddMenu.newMenuName, menu$(result)
    end if
wait

[keepOpen]
print #AddMenu.newMenuName,"!setfocus"
wait

[cancelNewMenu]   'Perform action for the button named 'cancelNewMenu'
    print #AddMenu.newMenuName,"!contents? test$"
    if trim$(test$)<>"" and menuCount < 20 and editMenuItemAction$<> "EDIT" then
        confirm "Do you want to save the Menu entered as "+chr$(13)+_
        test$+chr$(13)+" before closing this window?";t$
        if t$="yes" then gosub [addThisMenu]
    end if
    if selectFirst>0 then
        print #editMenu.menuList, "selectindex ";selectFirst
        result=selectFirst
        selectFirst=0
    end if
    close #AddMenu
wait

[clearMenuData]     'reset menu data arrays and indices
    for x = 0 to 20
        menu$(x) = ""
        for y = 0 to 30
            menuItem$(x, y) = ""
        next y
    next x
    menuCount = 0
if menuCount=0 then menu.offset=0
return
[acceptNewMenu]   'Perform action for the button named 'acceptNewMenu'
    r$=""
    if editMenuItemAction$<> "EDIT" then
        if menuCount=20 then
            notice "The maximum menu limit has been reached."
            close #AddMenu
            goto [selectMenuToEdit]
            wait
        end if
        gosub [addThisMenu]
    else
        print #AddMenu.newMenuName, "!contents? test$"
        menu$(result)=test$ 
        menuIsChanged=1
        print #editMenu.menuList,"reload"
    end if
    'For multiple Menu input of new menu titles
    if editMenuItemAction$<> "EDIT" then print #AddMenu.keepOpen,"value? r$"
    if r$="set" then
        if selectFirst=0 then selectFirst=menuCount
        if multiMenu=0 then print #AddMenu.exit,"&Done"
        multiMenu=1
        print #AddMenu.listbox,"reload"
        print #AddMenu.newMenuName, ""
        print #AddMenu.newMenuName,"!setfocus"
        wait
    else
        close #AddMenu
        goto [selectMenuToEdit]
    end if
wait

[addThisMenu] 'add this menu to the list of menus, and update the list
    print #AddMenu.newMenuName, "!contents? result$"
    if result$ = "" then notice "Please type a name for the new menu." :print #AddMenu.newMenuName,"!setfocus": wait
    menuIsChanged=1
    if editMenuItemAction$<> "EDIT" then menuCount = menuCount + 1
    menu$(menuCount) = result$
    print #editMenu.menuList,"reload"
    print #editMenu.menuList, "selectIndex ";menuCount
return

[removeMenu]   'remove a menu from the list of menus
    if menuCount = 0 then notice "No menus to remove." :wait

[acceptRemoveMenu]   'get the name of the selected item, and remove it
    print #editMenu.menuList, "selectionIndex? result"
    if result = 0 then notice "No item selected.  Menu not removed." : wait
    r=result
    result = result - 1
    iCount=0
   for z = result to menuCount
        menu$(z) = menu$(z+1)
        menuItemCount(z)=menuItemCount(z+1)
        for yy = 0 to 29
             menuItem$(z,yy)=menuItem$(z+1,yy)
             menuItem$(z+1,yy)=""
        next yy
     next z
    print #editMenu.menuList,"reload"
    if r < menuCount+1 then
        print #editMenu.menuList, "selectIndex ";r
    else
        result=result-1
        if result<1 then result=0
        print #editMenu.menuList, "selectIndex ";r-1
    end if
    result=result+1
    gosub [reloadLocalMenuItems]
    menuIsChanged=1
wait

[closeMenuEdit]   'close the menu editing dialog and redraw the form
    for x = 0 to 29 : menuItemLocal$(x) = "" : next x
    close #editMenu
    editMenuIsOpen = 0
    if menuCount=0 then menu.offset=0
    if menuIsChanged then gosub [redrawAll]
wait

[moveMenuUp] 'move the selected menu up the list
    'if there is no selection, or if the selected item is already on top, do nothing
    if result = 0 or result = 1 then wait
    tmpMenu$ = menu$(result-1)
    menu$(result-1) =menu$(result)
    menu$(result) = tmpMenu$
    holdCount1=menuItemCount(result)
    holdCount2=menuItemCount(result-1)
    for x = 0 to 29
          tmpMenuItem$(x) =" "
          tmpMenuItem$(x) = menuItem$(result-1,x)
    next x
    for x = 0 to 29
        if holdCount1 >0 then
            menuItem$(result-1,x) =menuItem$(result,x)
        else
            menuItem$(result-1,x)=""
        end if
    next x
    for x = 0 to 29
        if holdCount2 >0 then
        menuItem$(result,x) = tmpMenuItem$(x)
        else
        menuItem$(result,x)=""
        end if
    next x
    menuItemCount(result-1)=holdCount1
    menuItemCount(result)=holdCount2
    print #editMenu.menuList, "reload"
    if result>1 then result=result-1
    print #editMenu.menuList, "selectIndex ";result 'result-1
    menuIsChanged=1
    wait

[moveMenuDown]
    print #editMenu.menuList, "selectionIndex? result"
    if result = 0  or result >= menuCount then wait
    menuHold$= menu$(result)
    itemCountHold=menuItemCount(result)
    for y = 0 to 29
        menuItemHold$(y) = menuItem$(result, y)
    next y
    x= result
    menu$(x)=menu$(x+1)
    menuItemCount(x)=menuItemCount(x+1)
    for y=0 to  29
        menuItem$(x,y) = menuItem$(x+1,y)
    next y
    menu$(x+1)=menuHold$
    menuItemCount(x+1)=itemCountHold
    for y=0 to  29
        menuItem$(x+1,y) = menuItemHold$(y)
    next y
    x=x+1
    if x >menuCount then x=menuCount ''+1
    print #editMenu.menuList, "reload"
    print #editMenu.menuList, "setfocus"
    if result<menuCount then result=result+1
    print #editMenu.menuList, "selectIndex ";result
    menuIsChanged=1
wait

[moveMenuItemUp]   'Perform action for the button named 'moveMenuItemUp'
    print #editMenu.menuList, "selectionIndex? result"
    print #editMenu.menuItems, "selectionIndex? menuItemIndex"
    if menuItemIndex = 1 or menuItemIndex = 0 then wait 'was [inputloop]
    tmpMi$ = menuItem$(result, menuItemIndex-1)
    menuItem$(result, menuItemIndex - 1) = menuItem$(result, menuItemIndex - 2)
    menuItem$(result, menuItemIndex - 2) = tmpMi$
    gosub [reloadLocalMenuItems]
    menuItemIndex = menuItemIndex - 1
    print #editMenu.menuItems, "selectIndex "; menuItemIndex
wait

[moveMenuItemDown]
    tempDex=0
    print #editMenu.menuList, "selectionIndex? result"
    if result = 0 then wait
    print #editMenu.menuItems, "selectionIndex? menuItemIndex"
    for x=29 to 1 step-1
        if menuItem$(result,x)="" then tempDex=x
    next x
    if menuItemIndex >=tempDex or result = 0 then wait
    if menuItemIndex = menuItemCount(result) or menuItemIndex = 0 then wait
    tmpMi$ = menuItem$(result, menuItemIndex - 1)
    menuItem$(result, menuItemIndex - 1) = menuItem$(result, menuItemIndex)
    menuItem$(result, menuItemIndex) = tmpMi$
    gosub [reloadLocalMenuItems]
    menuItemIndex = menuItemIndex + 1
    print #editMenu.menuItems, "selectIndex "; menuItemIndex
wait

[formIsModified]    'the form has been modified, offer to save
    if objectCount < 2 then return  ' if there are no objects, don't offer to save form

'from LB Workshop
'Thanks Alyce!
    saveMsg$= "Would like to save the changes to " + formName$ + " first?"
    calldll #user32, "MessageBeep", _MB_ICONQUESTION  as long, beepResult as boolean
    mbflags = _MB_ICONQUESTION OR _MB_YESNOCANCEL
    calldll #user32, "MessageBoxA",0 as long,saveMsg$ as ptr, _
    "Oops.." as ptr,mbflags as long,mbResult as long
    cancelOpp=0
    if mbResult=2 then cancelOpp=1    'mbResult CODES: 2=cancel 6=yes 7=no
    if mbResult=6 then
        if formName$="" or formName$="untitled.ffa" then gosub [auxSave]
        gosub [saveFormSubroutine]
    end if
    if mbResult=7 then isModified = 1
    return

[settingsDialog]    'edit the settings for FreeForm
    WindowWidth = 305
    WindowHeight = 385
    UpperLeftX=int((DisplayWidth-WindowWidth)/2)
    UpperLeftY=100
    groupbox #settings.gbg,"",-1,-7,298,362 '268
    groupbox #settings.gbg,"",10, 1,278,105
    groupbox #settings.gbg,"",10, 1,278,318
    statictext #settings.st1,"Default Font",        22,111,100, 18   '129
    statictext #settings.st1,"Bmp Path",            22,161,100, 18   '129
    statictext #settings.st1,"Default Window Type", 22,216,120, 18   '129
    statictext #settings.st1,"Default Handle",      22,266,100, 18  '129
    checkbox #settings.creationInspect, "&Inspect each control when created", [creationInspectSet], [creationInspectClear], 22, 12,200, 19
    checkbox #settings.displayOrdering, "&Display control ordering", [displayOrderingSet], [displayOrderingReset],          22, 34,200, 19
    checkbox #settings.displayTooltips, "&Use Tooltips in Freeform", [displayToolTipSet], [displayToolTipReset],            22, 56,200, 19
    checkbox #settings.promptOnExit ,   "&Prompt when exiting Freeform",[promptOnExit],[dontPrompt],                        22, 78,200, 19
    textbox #settings.dFont,22,128,206,23
    textbox #settings.dbmpP,22,178,206,23
    combobox #settings.dType,winType$(),[dTypeSelect],22,235,256,150
    textbox #settings.dHndl,22,285,256,23    '22,188,206,23
    button #settings, "&Select",[dFontSelect],   UL,230,129, 48, 23
    button #settings, "&Select",[dBmpPathSelect],UL,230,179, 48, 23
    button #settings, "&Accept",[settingsAccept],UL,119,325, 80, 24
    button #settings, "&Cancel",[settingsCancel],UL,199,325, 80, 24
    open "Default Settings" for dialog_modal as #settings
    print #settings, "trapclose [settingsCancel]"
    if createInspect =1   then print #settings.creationInspect,"set"
    if displayOrdering =1 then print #settings.displayOrdering,"set"
    if tooltipFlag = 1    then print #settings.displayTooltips,"set"
    if promptOnExit=1     then print #settings.promptOnExit ,  "set"
    'call EnableControl hwnd(#settings.dFont),0
    print #settings.dFont,dFont$
    print #settings.dHndl,defaultWinHandle$
    print  #settings.dType,"select ";defaultWindowType$ 
    print #settings.dbmpP,bmpPath$
wait
[dBmpPathSelect]
    dPath$=getFolder$(hwnd(#settings),"Please select bmp folder")
    if trim$(dPath$)="" then  dPath$=bmpPath$
    print #settings.dbmpP,dPath$
wait

[dTypeSelect]
    print  #settings.dType,"selectionindex? wDex";
    if wDex <>0 then defaultWindowType$=winType$(wDex-1)
wait

[dFontSelect]
    chosenFont$=""
    fontdialog font$(1), chosenFont$
    if chosenFont$<>"" then
        font$(1)=chosenFont$
        print #settings.dFont,font$(1)
        dFont$=chosenFont$
    end if
wait

[displayToolTipSet] 'set value for always using tooltips
    if tooltipFlag = 0 then gosub [addTooltips]
    tooltipFlag = 1
    displayToolTip=1
    TooltipsOn=1
    wait
[displayToolTipReset]
    if TooltipsOn=1 then 'close #cctl 'WM_DESTROY
        CallDLL #user32, "SendMessageA", hTip As long, _
        _WM_DESTROY  As long, w As long, l As long, re As long
    end if
   TooltipsOn=0
   tooltipFlag = 0
   displayToolTip=0
   wait

[creationInspectSet]   'set value for inspect on create
    createInspect = 1
    wait

[creationInspectClear]   'set value for no inspect on create
    createInspect = 0
    wait

[displayOrderingSet]   'set value for displaying of control ordering
    displayOrdering  = 1
    wait

[displayOrderingReset]   'set value for non-displaying of control ordering
    displayOrdering  = 0
    wait
[promptOnExit]
    promptOnExit=1
    wait
[dontPrompt]
    promptOnExit=0
    wait
[settingsAccept]   'accept the settings
    print #settings.dFont,"!contents? df$"
    print #settings.dbmpP,"!contents? bmpPath$"
    if trim$(bmpPath$)="" then bmpPath$=DefaultDir$+"\bmp\"
    if right$(bmpPath$,1)<>"\" then bmpPath$=bmpPath$+"\"
    font$(1)=df$
    print #settings.dHndl,"!contents? defaultWinHandle$"
    if trim$(defaultWinHandle$)="" then defaultWinHandle$="#main"
    if left$(defaultWinHandle$,1)<>"#" then defaultWinHandle$="#"+defaultWinHandle$
    close #settings
    print #form, "font ";font$(1)
    gosub [saveIniFile]
    gosub [redrawAll]
    wait

[settingsCancel]   'discard any settings changes
    close #settings
wait


[loadIniFile]   'load the user preferences
'check to see if ffrm3019 exists
    'if fileExists(DefaultDir$,ffIni$) then
     if fileExists(DefaultDir$, "ffrm3019.ini") then
        open "ffrm3019.ini" for input as #ini
            input #ini, xInterval   'snap to x
            input #ini, yInterval   'snap to y
            input #ini, snapOn      'snap to on/off
            input #ini, createInspect 'inspect each control when created
            input #ini, displayOrdering 'display control ordering
            input #ini, displayFormat
            input #ini, displayToolTip ' 1 = Use tooltips  0 = don't
            input #ini, libertyexe$
            input #ini, gridVisibleOn
            input #ini, infoboxOpen
            input #ini, promptOnExit
'user defaults
            input #ini, defaultWindowType$ 
            input #ini, defaultWinHandle$ 
            input #ini, dFont$ 
            input #ini, lastPath$
            input #ini, bmpPath$

            input #ini,incPath$

            if trim$(defaultWinHandle$)="" then defaultWinHandle$="#main"
            if defaultWindowType$="" then defaultWindowType$="window"
            if dFont$="" then dFont$="ms_sans_serif 10"
            if lastPath$="For future use." or trim$(lastPath$)=""  then lastPath$=DefaultDir$
            if bmpPath$="For future use." or trim$(bmpPath$)="" then bmpPath$=DefaultDir$+"\bmp"
            windowType$=defaultWindowType$ 
            winHandle$=defaultWinHandle$
            font$(1)=dFont$
            xInterval(1)=xInterval
            yInterval(1)=yInterval

'these are already in file and may be used for future
            for ini=1 to 47
                input #ini, na$
            next ini
        close #ini
    end if
    return

[saveIniFile]   'save the user preferences
    open DefaultDir$+"\ffrm3019.ini" for output as #ini
        print #ini, xInterval
        print #ini, yInterval
        print #ini, snapOn
        print #ini, createInspect
        print #ini, displayOrdering
        print #ini, displayFormat
        print #ini, displayToolTip
        print #ini, libertyexe$
        print #ini, gridVisibleOn
        print #ini, infoboxOpen
        print #ini, promptOnExit
'user defaults
        print #ini, defaultWindowType$ '  winType$
        print #ini,  defaultWinHandle$ 
        if trim$(dFont$)="" then dFont$="ms_sans_serif 10"
        print #ini,dFont$
        print #ini, lastPath$
        print #ini, bmpPath$
        print #ini,incPath$

'future
        for ini=1 to 47
            print #ini, "For future use."
        next ini
    close #ini
RETURN

[copyControl] ' Copy the selected control
if objectCount =101 then [controlsAreMaxed]
    if index < 2 then [inputLoop]
    gosub [selectDeselect]
    objectCount = objectCount + 1
    idx = index
        type$(objectCount) = type$(idx)
        label$(objectCount) = label$(idx)
        names$(objectCount) = type$(idx)+str$(objectCount-1)
        xOrg(objectCount) = xOrg(idx) + 10
        yOrg(objectCount) = yOrg(idx) + 10
        width(objectCount) = width(idx)
        height(objectCount) = height(idx)
        corner$(objectCount) = corner$(idx)
        segment(objectCount) = segment(idx)
        handle$(objectCount) = handle$(idx)
        bmpName$(objectCount) = bmpName$(idx)
        bmpFileName$(objectCount) = bmpFileName$(idx)
        arrayName$(objectCount) = arrayName$(idx)
        tooltip$(objectCount) = tooltip$(idx)
        boxcolor$(objectCount) = boxcolor$(idx)
        controlFont$(objectCount)=controlFont$(idx)

    if type$(idx) = "button" then [copyButton]
    if type$(idx) = "textbox" then [copyField]
    if type$(idx) = "textedit" then [copyTextEdit]
    if type$(idx) = "combobox" then [copyComboBox]
    if type$(idx) = "listbox" then [copyListBox]
    if type$(idx) = "statictext" then [copyStaticText]
    if type$(idx) = "groupbox" then [copyGroupBox]
    if type$(idx) = "graphicbox" then [copyGraphicBox]
    if type$(idx) = "radiobutton" then [copyRadioButton]
    if type$(idx) = "checkbox" then [copyCheckBox]
    if type$(idx) = "bmpbutton" then [copyBmpButton]
    wait

[copyButton]     'copies a button to the form
    branchLabel$(objectCount) = "["+names$(objectCount)+"Click]"
    text$ = label$(objectCount)
    newControlNumber = newControlNumber + 1
    idx = objectCount
    gosub [renderButton]
    gosub [redrawAll]
    index = objectCount
    gosub [selectDeselect]
    wait

[copyBmpButton]     'copies a new bmpButton to the form
    branchLabel$(objectCount) = "["+names$(objectCount)+"Click]"
    text$ = label$(objectCount)
    newControlNumber = newControlNumber + 1
    idx = objectCount
    gosub [renderBmpButton]
    gosub [redrawAll]
    index = objectCount
    gosub [selectDeselect]
    wait

[copyField]     'copies a new field (textBox) to the form
    text$ = label$(objectCount)
    newControlNumber = newControlNumber + 1
    idx = objectCount
    gosub [renderTextBox]
    gosub [redrawAll]
    index = objectCount
    gosub [selectDeselect]
    wait

[copyTextEdit]     'copies a new field (textBox) to the form
    text$ = label$(objectCount)
    newControlNumber = newControlNumber + 1
    idx = objectCount
    gosub [renderTextEdit]
    gosub [redrawAll]
    index = objectCount
    gosub [selectDeselect]
    textEditControl=textEditControl+1
    wait

[copyComboBox]     'copies a new combobox to the form
    text$ = label$(objectCount)
    branchLabel$(objectCount) = "["+names$(objectCount)+"DoubleClick]"
    newControlNumber = newControlNumber + 1
    idx = objectCount
    comboStatus=1
    gosub [renderComboBox]
    gosub [redrawAll]
    index = objectCount
    gosub [selectDeselect]
    wait

[copyListBox]     'copies a new listbox to the form
    text$ = label$(objectCount)
    branchLabel$(objectCount) = "["+names$(objectCount)+"DoubleClick]"
    newControlNumber = newControlNumber + 1
    idx = objectCount
    gosub [renderListBox]
    gosub [redrawAll]
    index = objectCount
    gosub [selectDeselect]
    wait

[copyStaticText]     'copies statictext to the form
    text$ = label$(objectCount)
    newControlNumber = newControlNumber + 1
    idx = objectCount
    gosub [renderStaticText]
    gosub [redrawAll]
    index = objectCount
    gosub [selectDeselect]
    wait

[copyGroupBox]     'copies groupbox to the form
    text$ = label$(objectCount)
    newControlNumber = newControlNumber + 1
    idx = objectCount
    gosub [renderGroupBox]
    gosub [redrawAll]
    index = objectCount
    gosub [selectDeselect]
    wait

[copyGraphicBox]     'copies graphicbox to the form
    text$ = label$(objectCount)
    newControlNumber = newControlNumber + 1
    idx = objectCount
    gosub [renderGraphicBox]
    gosub [redrawAll]
    index = objectCount
    gosub [selectDeselect]
    wait

[copyRadioButton]     'copies radiobutton to the form
    text$ = label$(objectCount)
    branchLabel$(objectCount) = "["+names$(objectCount)+"Set] ["+names$(objectCount)+"Reset]"
    newControlNumber = newControlNumber + 1
    idx = objectCount
    gosub [renderRadioButton]
    gosub [redrawAll]
    index = objectCount
    gosub [selectDeselect]
    wait

[copyCheckBox]     'copies checkbox to the form
    text$ = label$(objectCount)
    branchLabel$(objectCount) = "["+names$(objectCount)+"Set] ["+names$(objectCount)+"Reset]"
    newControlNumber = newControlNumber + 1
    idx = objectCount
    gosub [renderCheckBox]
    gosub [redrawAll]
    index = objectCount
    gosub [selectDeselect]
    wait

[popupMenu] ' Open context-sensitive popup menus
    if index <= 1 then
        PopupMenu "Properties",           [inspectControl],|,_
                "&List all controls",     [displayColtrolList],|,_
                "&Menu Editor",           [editMenus],|,_
                "&Auto Snap to Grid",     [gridDialog],_
                "&Settings",              [settingsDialog],_
                "&Produce Code",          [produceCode],_
                "Produce Code + &Outline",[produceCodeAndOutline],_
                "&Test Code",             [testCode]
        else
            if type$(index) = "combobox" or type$(index) = "listbox" or type$(index) = "textbox" or type$(index) = "textedit" then
                popupmenu "Copy",         [copyControl],_
                          "Delete",       [deleteControl],_
                          "Properties",   [inspectControl],|,_
                          "Move to Front",[moveToFront],_
                          "Move to Back", [moveToBack]
            else
                if type$(index) = "bmpbutton" then
                    popupmenu "Copy",[copyControl],"Delete",[deleteControl],"Properties",[inspectControl],"Change Bitmap",[changeBmpButton],"Move to Front",[moveToFront],"Move to Back",[moveToBack]
                else
                    popupmenu "Copy",[copyControl],"Delete",[deleteControl],"Properties",[inspectControl],"Move to Front",[moveToFront],"Move to Back",[moveToBack]
                end if
        end if
    end if
    wait

[addTooltips] ' Add tooltips to Freeform... won't work in Windows NT!
hTip=CreateTooltip(hParent)
    Call AddToolTip Hwnd(#form.load)    , hTip , "Open File"
    Call AddToolTip Hwnd(#form.save)    , hTip , "Save File"
    Call AddToolTip Hwnd(#form.static)  , hTip , "Static Text"
    Call AddToolTip Hwnd(#form.field)   , hTip , "Text Box"
    Call AddToolTip Hwnd(#form.button)  , hTip , "Button"
    Call AddToolTip Hwnd(#form.bmp)     , hTip , "BmpButton"
    Call AddToolTip Hwnd(#form.list)    , hTip , "Listbox"
    Call AddToolTip Hwnd(#form.combo)   , hTip , "Combobox"
    Call AddToolTip Hwnd(#form.radio)   , hTip , "Radiobutton"
    Call AddToolTip Hwnd(#form.check)   , hTip , "Checkbox"
    Call AddToolTip Hwnd(#form.group)   , hTip , "Groupbox"
    Call AddToolTip Hwnd(#form.edit)    , hTip , "Texteditor"
    Call AddToolTip Hwnd(#form.graphic) , hTip , "Graphicbox"
    Call AddToolTip Hwnd(#form.inspect) , hTip , "Inspect Control"
    Call AddToolTip Hwnd(#form.delete)  , hTip , "Delete Control"
    Call AddToolTip Hwnd(#form.infront) , hTip , "Move to Front"
    Call AddToolTip Hwnd(#form.inback)  , hTip , "Send to Back"
    Call AddToolTip Hwnd(#form.code)    , hTip , "Produce Code"
    Call AddToolTip Hwnd(#form.outline) , hTip , "Produce Code and Outline"
    Call AddToolTip Hwnd(#form.runner)  , hTip , "Test Form"
    Call AddToolTip Hwnd(#form.cut)     , hTip , "Not Active Yet"
    Call AddToolTip Hwnd(#form.copy)    , hTip , "Copy Element"
    Call AddToolTip Hwnd(#form.paste)   , hTip , "Not Active Yet"
    Call AddToolTip Hwnd(#form.new)     , hTip , "New File"
    TooltipsOn=1    'flag so we can close tips
RETURN

'this code lifted from the LB open source editor
[readyRun]' ** MAKE A TEMP FILE TO RUN IN LIBERTY BASIC
    print #code, "!selectall";
    '** GET CONTENTS OF TEXTEDITOR AND SAVE TO TEMPFILE
    print #code, "!contents?"
    input #code, saveit$ 
    filePath$=DefaultDir$
    if right$(filePath$,1)<>"\" then filePath$=filePath$+"\"
    tempfilename$=filePath$+"tempfile.bas"
    open tempfilename$ for output as #temp
    print #temp, saveit$
    close #temp
    close #code
    codeIsOpen = 0
    if libertyexe$="" then gosub [findLiberty]
    RETURN

[findLiberty]'** FIND LIBERTY.EXE
    lbPath$=DefaultDir$ 'see if Liberty is in this folder
    if right$(lbPath$,1)<>"\" then lbPath$=lbPath$+"\"
    DIM info$(10, 10)
    files lbPath$,"Liberty.exe", info$(
    check=val(info$(0, 0))
    if check=0 then
        'Liberty BASIC is not in this folder so prompt user to find it.
        filedialog "Find Liberty.exe","*.exe",libertyexe$ 
    else
        libertyexe$=lbPath$+"Liberty.exe" 'Liberty BASIC is in this folder.
   end if
    RETURN

[testRun]
    gosub [readyRun]
    if libertyexe$ = "" then notice "Liberty BASIC not located!": goto [inputLoop]
    for iDex= 1 to len(libertyexe$)
    if mid$(libertyexe$,iDex,1)="\" then iniDelimit=iDex
    next iDex
    iniPath$=left$(libertyexe$,iniDelimit)
    DIM info$(10, 10)
    files iniPath$,"lbasic303hold.tmp", info$(
    check=val(info$(0, 0))
    if check =0 then
        originalIni$=iniPath$+"lbasic303.ini"
        tempIni$=iniPath$+"lbasic303hold.tmp"
        open originalIni$ for input as #original
        open  tempIni$ for output as #copy
        print #copy, input$(#original, lof(#original));
        close #original
        close #copy
    end if
    tfname$ = GetShortPathName$(tempfilename$)
    run libertyexe$ + " -R -A "+tfname$
wait
[openWindowProperties]


[inspectControl]'pop up a dialog for displaying/modifying control properties
    inspectIsOpen = 1
    gbAdj=0
    if index >1 then
    oldDex=index
    gbAdj= 58 ' 33
        gosub [deselectOnly]
    index=oldDex
end if
    if index<1 then index=1
    WindowWidth =230 ' 180
    WindowHeight =309 + gbAdj
    UpperLeftY=66
'   Adjust prop dialog to open to right side of control if there is room,
'   otherwise open to left side of control.
    testIt=xOrg(index)-xOrg+width(index)+9
    if testIt < DisplayWidth-180 then
        UpperLeftX=xOrg(index)-xOrg+width(index)+9
    else
        UpperLeftX=xOrg(index)-xOrg-175
    end if
'Oh no!....... Groupbox Graphics strikes again! <G>#inspectDialog
    groupbox #inspect.gbg1,"",0,-5,223,285+gbAdj
    groupbox #inspect.gbg2,"",0,-5,223,247+gbAdj
    groupbox #inspect.gbg3,"",0,235+gbAdj,223,44
    if index>1 then  'for controls
        statictext #inspect.sx, "X-Org",    10, 35, 48, 18
        statictext #inspect.sy, "Y-Org",    10, 57, 48, 18
        statictext #inspect.sw, "Width",    10, 79, 48, 18
        statictext #inspect.sh, "Height",   10,101, 48, 18
        statictext #inspect.st, "Type",     10, 10, 48, 18
        statictext #inspect.type,"Type",    60, 11, 90, 18
        statictext #inspect.sc,  "Caption", 10,123, 48, 18
        statictext #inspect.sb,  "Branch",  10,145, 48, 18
        statictext #inspect.se,  ".ext",    10,167, 48, 18
        statictext #inspect.sa,  "Array(",  10,189, 48, 18
        statictext #inspect.si,  "Tooltip", 10,211, 48, 18
        statictext #inspect.sq,  "Boxcolor",10,233, 48, 18
        textbox #inspect.x,                 60, 31,150, 20
        textbox #inspect.y,                 60, 53,150, 20
        textbox #inspect.w,                 60, 75,150, 20
        textbox #inspect.h,                 60, 97,150, 20
        textbox #inspect.labelField,        60,119,150, 20
        textbox #inspect.branchLabelField,  60,141,150, 20
        textbox #inspect.nameField,         60,163,150, 20
        textbox #inspect.arrayNameField,    60,185,150, 20
        textbox #inspect.tooltip,           60,207,150, 20
        combobox #inspect.boxcolor, colorType$(, [inspectSelectColor], 60,229,150,200
        button #inspect.font, "Font",[selControlFont],ul, 10,250, 48, 18
        textbox #inspect.controlFont,       60,250,150, 20
        textbox #inspect.incCode,           60,275,150, 20
        button #inspect.include, "Import",[importCode],ul, 10,276, 48, 18
    else   'for Window
'get rid of multi #inspect.x etc and statictexts
        statictext #inspect.st, "Win Type", 10, 10, 48, 18
        statictext #inspect.st, "Handle",   10, 33, 48, 18
        statictext #inspect.sx, "X-Org",    10, 57, 48, 18
        statictext #inspect.sy, "Y-Org",    10, 79, 48, 18
        statictext #inspect.sw, "Width",    10, 101, 48, 18
        statictext #inspect.sh, "Height",   10,123, 48, 18
        statictext #inspect.sc, "TitleBar", 10,145, 48, 18
        statictext #inspect.sq, "FG Color", 10,167, 48, 18
        statictext #inspect.si, "BG Color", 10,189, 48, 18
        combobox #inspect.type,winType$(),[newWinType],  60, 11,150,200
        textbox #inspect.handle,            60, 31, 150, 20
        textbox #inspect.x,                 60, 53, 150, 20
        textbox #inspect.y,                 60, 75, 150, 20
        textbox #inspect.w,                 60, 97, 150, 20
        textbox #inspect.h,                 60,119, 150, 20
        textbox #inspect.labelField,        60,141, 150, 20
        combobox #inspect.fgColor,colorType$(,[fgInspectSelectColor],  60,163, 150,200
        combobox #inspect.bgColor,colorType$(, [bgInspectSelectColor], 60,185,150,200
        textbox #inspect.guiFont,       60,207, 150, 20
        button #inspect.font, "Font",[selWinFont],ul, 10,209, 48, 18
    end if

    iBh=249+gbAdj   'button adjustment
    button #inspect.default,"&Accept",[acceptInspect],UL,60,iBh,75,24
    button #inspect.cancel,"&Cancel",[cancelInspect],UL,135,iBh,77,24
    if index>1 then
        Open "Control Properties" for dialog_modal as #inspect
        print #inspect.x, "!setfocus"
    else
        Open "Window Properties" for dialog_modal as #inspect
        print #inspect.type,"setfocus"
    end if
    print #inspect, "trapclose [cancelInspect]";
    print #inspect, "font ms_sans_serif 8"
    if index>1 then

'display the file name only
        print #inspect.incCode,fileSpec$(incFile$(index),0)
        if controlFont$(index)="" then controlFont$(index)=font$(1)
        print #inspect.controlFont,controlFont$(index)
'Turn off font button for groupbox and bmpbuttons.
        if type$(index)="groupbox" or type$(index)="bmpbutton" then_
        call EnableControl hwnd(#inspect.font),0
'Do not allow user to "hand enter" data in the font textbox.
        call EnableControl hwnd(#inspect.controlFont),0
        colorType$(19) = ""
        if type$(index)="graphicbox" then colorType$(19) = "RGB Select"
        print #inspect.boxcolor,"reload"
        if boxcolor$(index)="" then boxcolor$(index)="white"
        print #inspect.boxcolor, "!";boxcolor$(index)
        print #inspect.type, upper$(type$(index))
        print #inspect.labelField, label$(index)
        print #inspect.nameField, names$(index)
        print #inspect.branchLabelField, branchLabel$(index)
        print #inspect.arrayNameField, arrayName$(index)
        print #inspect.tooltip, tooltip$(index)
        dummyx$=str$(xOrg(index)-xOrg-4)
        dummyy$=str$(yOrg(index)-yOrg-20-4)
        print #inspect.x, dummyx$
        print #inspect.y, dummyy$
        print #inspect.w, str$(width(index))
        print #inspect.h, str$(height(index))
        if instr(" button statictext checkbox radiobutton graphicbox groupbox ", type$(index)) = 0 then
            print #inspect.labelField, "n/a"
            call EnableControl hwnd(#inspect.labelField),0
        end if
        if instr(controlsThatBranch$, type$(index)) = 0 then
            print #inspect.branchLabelField, "n/a"
            call EnableControl hwnd(#inspect.branchLabelField),0
            call EnableControl hwnd(#inspect.incCode),0
            call EnableControl hwnd(#inspect.include),0
        end if
        if instr(" listbox combobox ", type$(index)) > 0 then
            print #inspect.arrayNameField, arrayName$(index)
         else
             print #inspect.arrayNameField, "n/a"
             call EnableControl hwnd(#inspect.arrayNameField),0
        end if
    else
        if trim$(windowType$)="" then windowType$="window"
        print #inspect.type,"select ";windowType$
        colorType$(19) = ""
        if instr(windowType$,"graphics")>0 then  colorType$(19) = "RGB Select"
        print #inspect.fgColor,"reload"
        print #inspect.bgColor,"reload"
        print #inspect.handle, winHandle$
        call EnableControl hwnd(#inspect.guiFont),0
        if windowCenterOnScreen = 1 then
            print #inspect.x,"Center"
            print #inspect.y,"Center"
        else
            print #inspect.x,windowUpperLeftX
            print #inspect.y, windowUpperLeftY
        end if
        print #inspect.w,windowXExtent
        print #inspect.h,windowYExtent
        print #inspect.labelField, windowLabel$
        print #inspect.guiFont,font$(1)
        print #inspect.fgColor,"!";currentForegroundColor$
        print #inspect.bgColor,"!";currentBackgroundColor$
        oldBgColor$=currentBackgroundColor$
    end if
    wait

[newWinType]   'select the type of window desired

    print #inspect.type, "selection? defaultType$"
    colorType$(19) = ""
    if instr(defaultType$,"graphics")>0 then colorType$(19) = "RGB Select"
    if index>1 then
        print #inspect.boxcolor,"reload"
        print #inspect.boxcolor, "!";boxcolor$(index)
    else
        print #inspect.fgColor,"reload"
        print #inspect.bgColor,"reload"
        print #inspect.fgColor,"!";currentForegroundColor$
        print #inspect.bgColor,"!";currentBackgroundColor$
    end if
    if windowType$ <> defaultType$ then windowType$ = defaultType$
    gosub [redrawAll]
    wait

[fgInspectSelectColor]
    print #inspect.fgColor,"selectionindex? cDex"
    if cDex=19 then
        print #inspect.fgColor,"selectindex 0"
        print #inspect.fgColor,"!";oldFgColor$
        colordialog oldFgColor$, chosen$
        print #inspect.fgColor,"!";chosen$
        if chosen$<> "" then oldFgColor$=chosen$
        fgRGB=1
    else
        oldFgColor$= colorType$(cDex)
        fgRGB=0
    end if
    print #inspect.fgColor,"selectindex 0"
    print #inspect.fgColor,"!";oldFgColor$
wait

[bgInspectSelectColor]
    print #inspect.bgColor,"selectionindex? cDex"
    if cDex=19 then
        print #inspect.bgColor,"!";oldBgColor$  'oldColor$
        colordialog oldBgColor$, chosen$
        if chosen$="" then chosen$=oldBgColor$ 
        print #inspect.bgColor,"!";chosen$
        if chosen$<> "" then
            oldBgColor$=chosen$ 
            bgRGB=1
            test$=oldBgColor$
            gosub [checkRGB]
            oldBgColor$=rgbTest$
            print #inspect.bgColor,"!";oldBgColor$
            defaultRgbBgColor$=oldBgColor$
        else
            print #inspect.bgColor,"!";oldBgColor$
            defaultRgbBgColor$=oldBgColor$
        end if
    else
        oldBgColor$= colorType$(cDex)
        bgRGB=0
    end if
    print #inspect.bgColor,"selectindex 0"
    print #inspect.bgColor,"!";oldBgColor$
    if colorType$<>oldBgColor$ then
        colorType$ =oldBgColor$
        wincolor$ = oldBgColor$
        currentBackgroundColor$ = oldBgColor$
    end if
wait
[inspectSelectColor] 'RGB Colors for graphicboxs
    print #inspect.boxcolor,"selectionindex? cDex"
    if cDex=19 then
        print #inspect.boxcolor,"!";oldBoxColor$
        colordialog oldBoxColor$, chosen$
        print #inspect.boxcolor,"!";oldBoxColor$
        if chosen$<> ""  then  oldBoxColor$=chosen$
         boxRGB=1
    else
        if cDex<19 then oldBoxColor$=colorType$(cDex)
        boxRGB=0
    end if
    print #inspect.boxcolor,"selectindex 0"
    print #inspect.boxcolor,"!";oldBoxColor$
    boxcolor$(index)= oldBoxColor$
    holdDex=index
    idx=index
    index=holdDex
wait

[selControlFont]
    if controlFont$(index)="" then  controlFont$(index)=dialogFont$
    cursor hourglass
    fontdialog controlFont$(index), chosenFont$
    cursor normal
    if chosenFont$="" then chosenFont$=font$(1)
    controlFont$(index)=chosenFont$
    print #inspect.controlFont,chosenFont$ 'winFont$
    gosub [inspectScanLoop]
wait

[selWinFont]
    if winFont$="" then  winFont$=font$(1) 'dialogFont$
    cursor hourglass
    fontdialog font$(1), chosenFont$
    cursor normal
    if chosenFont$<>"" then
        winFont$=chosenFont$
        print #inspect.guiFont,winFont$
    end if
wait
'==============================================================
'==============================================================
[importCode]
    incFile$=incFile$(index)
    gosub [Include]
    incFile$(index)=getInclude$
    print #inspect.incCode,fileSpec$(incFile$(index),0)

wait
'==================================================================
'==================================================================
[acceptInspect] 'set the properties as modified by the user
    isModified = 1  'the form has been modified

'WinType
    if windowType$ <> defaultType$ then windowType$ = defaultType$
    if left$(windowType$, 6) = "dialog" then loadbmp "systemBox", "bmp\95sysbxd.bmp"
    if left$(windowType$, 6) <> "dialog" then loadbmp "systemBox", "bmp\95sysbx.bmp"

    if index>1 then
        print #inspect.incCode,"!contents? test$"
        if trim$(test$)="" then incFile$(index)=""
        print #inspect.nameField, "!contents? names$" : names$(index) = names$
        branches = instr(controlsThatBranch$, type$(index))
        if branches > 0 then print #inspect.branchLabelField, "!contents? bLabel$"
        'Require branch labels for buttons and bmpbuttons.
        if instr("button bmpbutton  ", type$(index))>0 and trim$(bLabel$)="" then
            notice "Problem"+chr$(13)+"Branch label required"
            wait
        end if
        'Fix radiobutton and checkbox controls inner branch brackets.
        if type$(index)="radiobutton" or type$(index)="checkbox" then
            bL1$=word$(bLabel$, 1)
            bL2$=word$(bLabel$, 2)
            if right$(bL1$,1)<>"]" then bL1$=bL1$+"]"
            if left$(bL2$,1)<>"[" then bL2$="["+bL2$
            bLabel$=bL1$+" "+bL2$
        end if
        'Fix outer branch brackets for all controls
        'if type$(index)<>"radiobutton" and type$(index)<>"checkbox" then
        '  usesArray =instr("statictext textbox listbox groupbox graphicbox  ", type$(index))

        if left$(bLabel$,1)<>"[" then bLabel$="["+bLabel$
        if right$(bLabel$,1)<>"]" then bLabel$=bLabel$+"]"
        branchLabel$(index) = bLabel$
        usesArray = instr(" listbox combobox ", type$(index))
        if usesArray > 0 then print #inspect.arrayNameField, "!contents? aName$" : arrayName$(index) = aName$
        print #inspect.x, "!contents? dummy$" : xOrg(index)=val(dummy$)+xOrg+4
        print #inspect.y, "!contents? dummy$" : yOrg(index)=val(dummy$)+yOrg+24
        print #inspect.w, "!contents? dummy$" : width(index)=val(dummy$)
        print #inspect.h, "!contents? dummy$" : height(index)=val(dummy$)
        print #inspect.labelField, "!contents? label$" : label$(index) = label$ 
        checkRgb=1
        print #inspect.boxcolor, "contents? dummy$"
        for ct=1 to 18
            if dummy$=colorType$(ct) then checkRgb=0
        next ct
        'Allow rgb colors
        if checkRgb=1 then
            if type$(index)<>"graphicbox" then
                notice "Sorry"+chr$(13)+_
                "This is not a valid color for this type of control."+chr$(13)+_
                "Please select a color from the list provided."
                dummy$="white"
                wait
            end if
        end if
        test$=dummy$
        rgbControl=1
        gosub [checkRGB]
        rgbControl=0
'-----------------------------------------
        checkRgb=0
        boxcolor$(index) = dummy$
        if type$(index)="textbox" then fieldDefaultColor$=dummy$
        if type$(index)="listbox" then listboxDefaultColor$=dummy$
        if type$(index)="combobox" then comboboxDefaultColor$=dummy$
        if type$(index)="textedit" then texteditDefaultColor$=dummy$
        if type$(index)="graphicbox" then graphicboxDefaultColor$=dummy$
        print #inspect.tooltip, "!contents? dummy$"
        if tooltip$(index) <> "" and dummy$ = "" then tooltip$(index) = ""
        if dummy$ <> "" then tooltip$(index)=dummy$ 
    else
'*******************'get gui paremeters here '*******************
        print #inspect.type, "selection? defaultType$"
        if trim$(defaultType$)="" then defaultType$="window"
        if windowType$ <> defaultType$ then windowType$ = defaultType$
        if left$(windowType$, 6) = "dialog" then loadbmp "systemBox", "bmp\95sysbxd.bmp"
        if left$(windowType$, 6) <> "dialog" then loadbmp "systemBox", "bmp\95sysbx.bmp"

        if trim$(defaultType$)="" then defaultType$="window"
        print #inspect.handle,"!contents? winHandle$"
        if trim$(winHandle$)="" or trim$(winHandle$)="#" then winHandle$="#main"
        if left$(winHandle$, 1) <> "#" then winHandle$ = "#" + winHandle$
        print #inspect.x,"!contents? windowUpperLeftX$"
        print #inspect.y, "!contents? windowUpperLeftY$"
        print #inspect.w,"!contents? windowXExtent"
        print #inspect.h,"!contents? windowYExtent"
        if windowCenterOnScreen = 1 then
            if windowUpperLeftX$<>"Center" or windowUpperLeftY$<> "Center" then
                windowCenterOnScreen = 0
                windowUpperLeftX=val(windowUpperLeftX$)
                windowUpperLeftY=val(windowUpperLeftY$)
            else
                windowCenterOnScreen = 1
                windowUpperLeftX=0
                windowUpperLeftY=0
            end if
        end if
        width(index)=windowXExtent
        height(index)=windowYExtent
        print #inspect.labelField, "!contents? windowLabel$"
        print #inspect.guiFont,"!contents?  font$"
        print #inspect.fgColor,"contents?  fgColor$"
        print #inspect.bgColor,"contents?  bgColor$"
        if instr(defaultType$,"graphic")=0 then
        fg=1:bg=1
        fgColor$=trim$(fgColor$)
        bgColor$=trim$(bgColor$)
        for c=0 to 18
            if fgColor$=colorType$(c) then fg=0
            if bgColor$=colorType$(c) then bg=0
        next c


        if fg=1 or bg=1 then
            notice"Oops..."+chr$(13)+_
            "Rgb colors are not allowed in this type window."
            wait
        end if
    end if
    if fgColor$ <> "" then
        fg=0
        test$=fgColor$
        gosub[checkRGB]
        currentForegroundColor$=rgbTest$
    else
        currentForegroundColor$=fgColor$
    end if
    if bgColor$ <> "" then
        bg=0
        test$=bgColor$
        gosub[checkRGB]
        colorType$ = bgColor$
        wincolor$ = bgColor$
        currentBackgroundColor$ = bgColor$
    end if
end if
    if font$<>"" then font$(1)= font$ 
gosub [checkPosition]
    close #inspect
    inspectIsOpen = 0
timer 100,[testHandle]
    gosub [redrawAll]
    wait

[checkRGB]
    rTest$=" "
    gTest$=" "
    bTest$=" "
    LBColor=0   'check for standard colors
    test$=trim$(test$)
    for test=1 to 18
       if Lower$(colorType$(test))=Lower$(test$) then LBColor=test
    next test


    if rgbControl=0 then
    'make sure rgb is allowed in this type gui
      if inspectIsOpen = 1 then
        print #inspect.type, "selection? defaultType$"
            if instr(defaultType$,"graphics")=0 and LBColor=0 then
                notice "Rgb colors are not allowed in ";defaultType$;" windows."
                wait
            end if
       end if
    end if

    if LBColor then rTest$=colorType$(LBColor):goto [exitTest]
'now check for rgb errors
    rgbError=0
    rTest$= word$(test$, 1)
    gTest$= word$(test$, 2)
    bTest$= word$(test$, 3)
    lbTest$= word$(test$,4)
'look for illegal characters
    characterError=0
    testForChar$=rTest$+gTest$+bTest$
    for x=1 to len(testForChar$)
        a=asc(mid$(testForChar$,x,1))
        if a<40 or a>57 then characterError=1
    next x
    if characterError=1 then
        notice"Oops..."+chr$(13)+_
            "RGB error...."+chr$(13)+_
            testForChar$;" contains illegal character(s)."
       wait
    end if
    if len(rTest$)<1 or _
       len(gTest$)<1 or _
       len(bTest$)<1 then
        notice"Oops..."+chr$(13)+_
            "RGB error...."+chr$(13)+_
            "Rgb must be specified in 3 groups of at"+chr$(13)+_
            "least 1 and no more than 3 numbers:"+chr$(13)+_
            space$(10);"123 111 123"
        wait
    end if
    if val(rTest$)>255 then rgbError=2 :rebErrMsg$="Red"
    if val(bTest$)>255 then rgbError=2 :rebErrMsg$="Blue"
    if val(gTest$)>255 then rgbError=2 :rebErrMsg$="Green"
    if rgbError=2 then
        notice"Oops..."+chr$(13)+_
        "Number specifing ";rebErrMsg$;" is out of range."+chr$(13)+_
        "255 is the maximum allowed."
        wait
    end if
[exitTest]
    rgbTest$=rTest$+" "+gTest$+" "+bTest$
    rgbTest$=trim$(rgbTest$)
return
[cancelInspect]'close the inspector window
    close #inspect
timer 100,[testHandle]
    wait

[helpContents]
    gosub [deselectOnly]
    gosub [checkPosition]
help$= DefaultDir$+"\freeform.hlp"
    run "winhlp32 ";help$  'freeform.hlp"
    wait

[helpAbout]
    gosub [deselectOnly]
    gosub [checkPosition]
    notice "About..."+chr$(13)+_
            space$(9) +"Freeform3 for Liberty BASIC 3.0"+chr$(13)+_
            space$(22)+"v";ffVersion$+chr$(13)+chr$(13)+_
            space$(2) +"Copyright 1995 to 2003 Shoptalk Systems"+chr$(13)+_
            space$(18)+"All rights reserved"+chr$(13)+chr$(13)+_
                       "Freeform3 is a Liberty BASIC community project."
   wait

[menuSaveErr]
    confirm "This form has no controls and can not be saved. "+chr$(13)+_
    "If you continue, the MENU ITEMS that you entered will be lost."+chr$(13)+_
    chr$(13)+space$(20)+"Do you want to continue?"; answer$
    cancelOpp=0
    if  answer$="no" then cancelOpp=1
return

[quit]   'exit Freeform
    if objectCount <2 and menuCount > 0 then gosub [menuSaveErr]
    if isModified = 1 then gosub [formIsModified]

    if cancelOpp=1 then wait
    'quit freeform
    if promptOnExit=1 then
        confirm "Are you sure?"; answer$
        if answer$ = "no" then [inputLoop]
    end if
    gosub [saveIniFile]
    close #form
    if includeCode=1 then close #inc
    if codeIsOpen then close #code

    if TooltipsOn=1 then 'close #cctl 'WM_DESTROY
        CallDLL #user32, "SendMessageA", hwndTT As long, _
        _WM_DESTROY  As long, w As long, l As long, re As long
    end if
    if windPropOpen = 1 then close #windowProperties

    for iDex= 1 to len(libertyexe$)
        if mid$(libertyexe$,iDex,1)="\" then iniDelimit=iDex
    next iDex
    iniPath$=left$(libertyexe$,iniDelimit)
    originalIni$=iniPath$+"lbasic303hold.tmp"
    tempIni$=iniPath$+"lbasic303.ini"
    DIM info$(10, 10)
    files iniPath$,"lbasic303hold.tmp", info$(
    check=val(info$(0, 0))
    if check >0 then
        open originalIni$ for input as #original
        open tempIni$ for output as #copy
        print #copy, input$(#original, lof(#original));
        close #original
        close #copy
        kill originalIni$
    end if
    filePath$=DefaultDir$
    if right$(filePath$,1)<>"\" then filePath$=filePath$+"\"
    tempfilename$=filePath$+"tempfile.bas"
    files filePath$,"tempfile.bas", info$(
    check=val(info$(0, 0))
    if check >0 then kill tempfilename$
END:END:END



[toolTipOption]'Toggle tooltips on and off
    if toolTipControl=1 then
        toolTipControl=0 'turn tips off
      wC=8
    else
        wC=0
        toolTipControl=1 'turn tips on
     end if
     gosub [changeMenuText]
wait

[changeMenuText]
h=hwnd(#form)
    CallDLL #user32,"GetParent",h AS long,hParent AS long
    CallDll #user32,"GetMenu",hParent as long,hMenuBar as long
    CallDll #user32,"GetSubMenu",hMenuBar as long,4 as long,hSubMenu as long
    CallDll #user32,"GetMenuItemID",hSubMenu as long,3 as long,menu.id as long
    CallDll #user32,"GetDesktopWindow",hDesktop as long
    CallDLL #user32,"GetParent",hDesktop AS long,h AS long
    calldll #user32,"CheckMenuItem",hSubMenu As long,menu.id As long,wC As long,_     'checked=8, unchecked=0
    r as long
return


[checkPosition]
    warning=0
    adjuster=88
    if index>1 then
       mX =xOrg(index)-5
       mY = yOrg(index)-adjuster
    else
    mX =windowUpperLeftX
    mY = windowUpperLeftY
    end if
    mX$=str$(mX)
    mY$=str$(mY)
    mW$=str$(width(index))
    mH$=str$(height(index))
    if left$(mX$,1)="-" then mX$=mX$+space$(5)
    if left$(mY$,1)="-" then
        if len(mY$)=2 then mY$=mY$+space$(5)
        if len(mY$)=3 then mY$=mY$+space$(3)
    end if
    if mX>-1 then while len(mX$)<4:mX$="0"+mX$:wend
    if mY>-1 then while len(mY$)<4:mY$="0"+mY$:wend
    while len(mW$)<4:mW$="0"+mW$:wend
    while len(mH$)<4:mH$="0"+mH$:wend
    if index >0 then
       if index=1 and windowCenterOnScreen = 1 then
           mX$="X Y Centered"
           mY$=""
        else
            mX$="x "+mX$
            mY$="y "+mY$
        end if
         #form.xy,mX$;"  ";mY$
         #form.wh,"w ";mW$;"  h ";mH$
    else
         #form.xy,""
         #form.wh,""
    end if
return

[testHandle]
    calldll #user32, "GetActiveWindow",h as long
    gosub [inspectScanLoop]
    wait



'--------------------------------------------------
'--------- Field selector (highlighter)------------
[inspectScanLoop]
    calldll #user32,"GetFocus",httb as long
    if oldHttb<>httb then oldHttb=httb: call SelectText httb
return


[defineVariables]          'Define and dimension needed variables
    dim font$(3)            'font$(1)=user chosen font,font$(2)=titlebar font
    dim type$(110)          'Window type
    dim label$(110)         'Contol label
    dim names$(110)         'Control handle name
    dim xOrg(110)           'Control x-origin
    dim yOrg(110)           'Control y-origin
    dim width(110)          'Control width
    dim height(110)         'Control height
    dim corner$(110)
    dim branchLabel$(110)   'Branchlabel used by control
    dim segment(110)        'Segment, used for rendering control onscreen
    dim handle$(110)        '
    dim tooltip$(110)       '
    dim bmpName$(110)       'Name used for rendering bitmap buttons
    dim bmpFileName$(110)   'File spec for bitmap used as bitmap button
    dim arrayName$(110)     'Array name used by control
    dim boxcolor$(110)
    dim menu$(21)           'Menu name
    dim menuItem$(21, 30)   'Menu subitem name
    dim menuItemLocal$(30)  '
    dim menuItemCount(21)   '
    dim tmpMenuItem$(30)
    dim incFile$(110)       'used for importing code
    dim info$(10, 10)       'used for getting file listing info

    fieldDefaultColor$="white"
    listboxDefaultColor$="white"
    comboboxDefaultColor$="white"
    texteditDefaultColor$="white"
    graphicboxDefaultColor$="white"
    holdTextBoxColor$="white"
    holdListboxColor$="white"
    holdTextBoxColor$="white"
    holdComboBoxcolor$="white"
    holdTextEditColor$="white"
    ForegroundColor$="black"
    BackgroundColor$="buttonface"
    defaultForegroundColor$ = ForegroundColor$
    defaultBackgroundColor$ = BackgroundColor$
    currentForegroundColor$ = defaultForegroundColor$
    currentBackgroundColor$ = defaultBackgroundColor$
    windowComboboxColor$ = defaultComboboxColor$
    windowListboxColor$ = defaultListboxColor$
    windowTextboxColor$ = defaultTextboxColor$
    windowTexteditorColor$ = defaultTexteditorColor$
    wincolor$ = defaultBackgroundColor$
    textcolor$ = defaultForegroundColor$
    boxcolor$ = "white"
    formName$ = "untitled.ffa"
    windowXOrigin = 1
    windowYOrigin = 64
    windowXExtent = 550
    windowYExtent = 410
    menuCount = 0
    windowUpperLeftX = 0
    windowUpperLeftY = 0
    newControlNumber = 0
    windowLabel$ = "untitled"
    windowType$ = defaultWindowType$ 
    objectCount = 0
    winHandle$ =  defaultWinHandle$
    windowXExtent = 550
    windowYExtent = 410
    textEditControl=0
    makeStatusbar = 0
    bmpCount = 0
    wC=0
    redim boxcolor$(100)
    font$(1)=dFont$
    font$(2)="system 7 16"
    font$(3)="arial 10"
    dialogFont$=font$(1)
    toolTipControl=1
    newTitle$=title$+" - untitled"
    call changeTitleBar hParent, newTitle$

RETURN
[displayColtrolList]
    gosub [deselectOnly]
    gosub [checkPosition]
    dim dNames$(objectCount)
    dim dType$(objectCount)
    dim dBranchLabel$(objectCount)
    dim dXOrg$(objectCount)
    dim dYOrg$(objectCount)
    dim array$(objectCount)
    tail$=" controls"
    if  objectCount=2 then tail$=" control"
    t$="Controls for:  "+windowLabel$+"  ["+winHandle$+"]     "+str$(objectCount-1)+tail$
    for x=2 to objectCount 'set as columns
        dNames$(x)=names$(x)
            if len(dNames$(x))>22 then dNames$(x)=left$(dNames$(x),21)+"~"
            while len(dNames$(x))<22:dNames$(x)=dNames$(x)+" ":wend
        dType$(x)=type$(x)
            if len(dType$(x))>11 then dType$(x)=left$(dType$(x),10)+"~"
            while len(dType$(x))<11:dType$(x)=dType$(x)+" ":wend
         dXOrg$(x)=str$(xOrg(x)-xOrg-4)
            if len(dXOrg$(x))>4 then dXOrg$(x)=left$(dXOrg$(x),3)+"~"
            while len(dXOrg$(x))<4:dXOrg$(x)=dXOrg$(x)+" ":wend
         dYOrg$(x)=str$(yOrg(x)-yOrg-20-4)
            if len(dYOrg$(x))>4 then dYOrg$(x)=left$(dYOrg$(x),3)+"~"
            while len(dYOrg$(x))<4:dYOrg$(x)=dYOrg$(x)+" ":wend
        dBranchLabel$(x)=branchLabel$(x)
        array$(x)=dNames$(x)+"  "+_
                  dType$(x)+space$(2)+_
                  dXOrg$(x)+space$(2)+_
                  dYOrg$(x)+space$(2)+_
                  dBranchLabel$(x)
    next x
    WindowWidth =550
    WindowHeight =int(WindowWidth/2)
    UpperLeftX=int((DisplayWidth-WindowWidth)/2)
    UpperLeftY=int((DisplayHeight-WindowHeight)/2)
    BackgroundColor$ = "buttonface"
    ForegroundColor$ = "black"
    ListboxColor$=     "darkgray"
    groupbox #listControls.gbg1,"",5,-5,535,29
    groupbox #listControls.gbg1,"",5,-5,190,29
    groupbox #listControls.gbg2,"",193,-5,110,29
    groupbox #listControls.gbg2,"",300,-5, 47,29
    groupbox #listControls.gbg2,"",345,-5, 47,29
    statictext #listControls.st1,"Name (extension)", 10, 7,100, 18
    statictext #listControls.st2,"Type",            203, 7, 80, 18
    statictext #listControls.st3,"xOrg",            308, 7, 30, 18
    statictext #listControls.st4,"yOrg",            355, 7, 30, 18
    statictext #listControls.st5,"Branch",          405, 7,100, 18
    listbox #listControls.list, array$(, [selControl], 5, 25,WindowWidth-15,WindowHeight-60
    open t$ for dialog_modal as #listControls
    print #listControls, "font ms_sans_serif 0 8"
    print #listControls.list,"font Courier_New 10"
    print #listControls, "trapclose [quitListControls]"
    if objectCount>14 and objectCount<18 then_
    print #listControls.list,"selectindex ";objectCount-1
    print #listControls.list,"selectindex 1"
    print #listControls.list,"setfocus"
    wait 'wait here for input event

[selControl]  'Select a control to edit
    print #listControls.list,"selectionindex? dex"
    if dex=0 then wait
    index=dex +1
    close #listControls
    goto [inspectControl]

[quitListControls]
     close #listControls
print #form, "setfocus;when characterInput [key.pressed]"
wait

[controlsAreMaxed]
notice "Sorry..."+chr$(13)+_
       "The maximum number of controls has been reached."
print #form, "setfocus;when characterInput [key.pressed]"
wait

[addGrid]
notice "Sorry..."+chr$(13)+"Grid option is not ready yet."
wait
'--------------------------------------------------------------------------
'-------------------------- Subs and Functions ----------------------------
'--------------------------------------------------------------------------
SUB changeTitleBar h,newTitle$ 
    calldll #user32, "SetWindowTextA",h as long,newTitle$ as ptr,r as void
END SUB

'This sub is used when adding any control
SUB addControl type$, count, idx, width, height, text$, corner$,controlDefaultColor$
    controlFont$(idx)=font$(1)
    xOrg(idx) =5 +xInterval(1) '10
    yOrg(idx) = 88+yInterval(1) '100
    width(idx) = width
    height(idx) = height
    type$(idx) = type$
    names$(idx) = type$+str$(count)
    corner$(idx) = corner$
    label$(idx) = text$
    if controlDefaultColor$="" then
    boxcolor$(idx) = "white"
    else
    boxcolor$(idx) = controlDefaultColor$
    end if
End SUB

SUB copyControl type$, count, idx, width, height, text$, corner$, x, y
    xOrg(idx) = x
    yOrg(idx) = y
    names$(idx) = type$+str$(count)
    label$(idx) = text$
End SUB

'This function is used at the tail end of rendering any control
FUNCTION postRender(idx, displayOrdering,menu.offset)
    if displayOrdering then
        print #form, "color white ; backcolor black ; place " + str$(xOrg(idx)) + " " + str$(yOrg(idx)+12+menu.offset)
        print #form, "\" + str$(idx - 1)
    end if
    print #form, "down ; flush"
    print #form, "segment id"
    segment(idx) = id
END FUNCTION


FUNCTION checkQuit$(blc$,x,winHandle$)
       if blc$="[quit]" then blc$="[quit.";mid$(winHandle$, 2);"]"
       checkQuit$=blc$
END FUNCTION

SUB SelectText hTb
    l=300  'max field length highlighted
    a=177
    calldll #user32,"SendMessageA",hTb As Long,a As Long,0 As Long,l As long,r As Long
END SUB

SUB EnableControl hC,f   'turn controls off or on
     CallDLL #user32,"EnableWindow",hC As long,f As boolean,r As boolean
END SUB

FUNCTION CreateTooltip(hMain)
    Struct TOOLINFO, _
    cbSize As long, _
    uFlags As long, _
    hwnd As long, _
    uId As long, _
    rectLeft As long, _
    rectTop As long, _
    rectRight As long, _
    rectBottom As long, _
    hinst As long, _
    lpszText As ptr

    CallDLL #comctl32,"InitCommonControlsEx", _
    ret As void

    TOOLINFO.cbSize.struct = Len(TOOLINFO.struct)
    TOOLINFO.uFlags.struct = flags Or 17 'TTF_IDISHWND Or TTF_SUBCLASS
    TOOLINFO.hwnd.struct = hMain

    CallDLL #user32,"CreateWindowExA",_
    0 As long, _
    "tooltips_class32" As ptr, _
    0 As long, style As long, _
    _CW_USEDEFAULT As long, _
    _CW_USEDEFAULT As long, _
    _CW_USEDEFAULT As long, _
    _CW_USEDEFAULT As long, _
    hMain As long, _
    0 As long, _
    0 as long, _
    0 As long, _
    CreateTooltip As Long
END FUNCTION

SUB AddToolTip cHndl, hWnd, Text$
    TOOLINFO.uId.struct = cHndl
    TOOLINFO.lpszText.struct = Text$
    CallDLL #user32, "SendMessageA",_
    hWnd As long, _
    1028 As long, _
    0 As long, _
    TOOLINFO as ptr, _
    ret As long
END SUB

FUNCTION ReleaseTooltipMemory(hTip)
    CallDLL #user32, "SendMessageA",_
    hTip As long, _
    _WM_DESTROY  As long, _
    w As long, _
    l As long, _
    re As long
END FUNCTION

'Return a string without quotes
'This is used when getting typed input
FUNCTION noQuotes$(text$)
    for x = 1 to len(text$)
        if mid$(text$, x, 1) <> chr$(34) then
            noQuotes$ = noQuotes$ + mid$(text$, x, 1)
        end if
    next x
END FUNCTION

FUNCTION GetShortPathName$(lPath$)
    lPath$=lPath$+Chr$(0)
    sPath$=Space$(256)
    lenPath=Len(sPath$)
    Open "kernel32" For DLL As #k
    CallDLL #k, "GetShortPathNameA",lPath$ As ptr,_
    sPath$ As ptr,lenPath As long,r As long
    Close #k
    GetShortPathName$=Left$(sPath$,r)
END FUNCTION

FUNCTION fileExists(path$, filename$) ' Does file exist?
    files path$, filename$, info$(
    fileExists = val(info$(0, 0)) > 0
END FUNCTION

FUNCTION fileSpec$(FindProg$,flag)
'   0=File name  1=File path
    ProgLen=len(FindProg$)
    for x=1 to ProgLen
    if mid$(FindProg$,x,1)="\" then DelimiterHold=x
    next x
    if flag=0 then
        fileSpec$=right$(FindProg$, ProgLen-DelimiterHold)
    else
        fileSpec$=left$(FindProg$,DelimiterHold)
    end if
END FUNCTION
FUNCTION fixExtension$(fileName$) '
         if mid$(fileName$,1,len(fileName$)-4)="." then
         fixExtension$=left$(fileName$,len(fileName$)-3)+"ffa"
         else
        fixExtension$=fileName$
END FUNCTION
FUNCTION getFolder$(hWndOwner,msg$) 'GetFolder function by Alyce Watson
    BIF.RETURNONLYFSDIRS = 1
    MAX.PATH = 260
    STRUCT BrowseInfo,_
        hWndOwner As Long,_
        pIDLRoot As Long,_
        pszDisplayName As Long,_
        lpszTitle$ As ptr,_
        ulFlags As Long,_
        lpfnCallback As Long,_
        lParam As Long,_
        iImage As Long
    BrowseInfo.hWndOwner.struct = hWndOwner
    BrowseInfo.lpszTitle$.struct = msg$ 'txt1$
    BrowseInfo.ulFlags.struct = BIF.RETURNONLYFSDIRS
    calldll #shell32, "SHBrowseForFolder",BrowseInfo as struct,lpIDList as long
    If lpIDList>0 Then
        sPath$ = space$(MAX.PATH) + chr$(0)
        calldll #shell32, "SHGetPathFromIDList",lpIDList as long,sPath$ as ptr,r as long
        open "ole32" for dll as #ole
        calldll #ole, "CoTaskMemFree",lpIDList as long,r as long
        close #ole
        iNull = InStr(sPath$, chr$(0))
        If iNull Then
            getFolder$ = Left$(sPath$, iNull - 1)
        End If
    End If
END FUNCTION
'--------------------------------------------------------------------------
'----------------------- End Subs and Functions ---------------------------
'--------------------------------------------------------------------------
[Include]
    if includeCode=1 then close #inc
    includeCode=1
    if trim$(incFile$)="" or trim$((incFile$))="mt" then gosub [openInclude]
    WindowWidth=500
    WindowHeight=300
    UpperLeftX=int((DisplayWidth-WindowWidth)/2)
    UpperLeftY=int((DisplayHeight-WindowHeight)/2)
    texteditor #inc.code,0,25,494,229
    button  #inc.b1,"Save &Edit",      [saveEdit],     ul,  1,  3,100, 23
    button  #inc.b2,"Save as &Include",[saveAsInclude],ul,101,  3,100, 23
    button  #inc.b3,"&Accept",         [acceptInclude],ur,144,  3,100, 23
    button  #inc.b4,"&Close",          [quitInclude],  ur, 52,  3,100, 23
    menu #inc,""
    menu #inc,"&Files",_
              "&Open",           [openNewInclude],|,_
              "&Accept",         [acceptInclude],_
              "Save &Edit",      [saveEdit],_
              "Save as &Include",[saveAsInclude],|,_
              "&Cancel Include", [cancelInclude]
    open "Import Code" for window as #inc
    print  #inc.code,"!autoresize"
    print  #inc,"trapclose [quitInclude]"

    gosub [loadInclude]
wait
[openNewInclude]
    gosub [openInclude]
    gosub [loadInclude]
wait
[saveAsInclude]
    filedialog "Save as","*.inc",includeFile$
    if includeFile$<>"" then
        if right$(includeFile$,4)<>".inc" then includeFile$=includeFile$+".inc"
        'check to see if this file name is in use
        'do not allow an overwrite without a confirm
        if fileExists(fileSpec$(includeFile$,1),fileSpec$(includeFile$,0)) then
             confirm includeFile$+" already exists"+chr$(13)+_
            "Do you want to overwrite it?";conf$
             if lower$(conf$)<>"yes" then wait
        end if
        incFile$=includeFile$
    end if
    goto [saveIncFile]
wait
[saveEdit]
    includeFile$=incFile$

[saveIncFile]
    if includeFile$="" then wait
    print #inc.code,"!contents? string$";
    open includeFile$ for output as #toFile
        print #toFile,string$ 
    close #toFile
    notice includeFile$;" saved."
wait

[openInclude]
    if incPath$="" then incPath$=path$
    includeTemplate$=incPath$+"*.inc;*.bas"
    filedialog "Open for include",includeTemplate$,incFile$
    includeFile$=incFile$
    incPath$=fileSpec$(includeFile$,1)
return
[loadInclude]
    if trim$(incFile$)="" then return 'includeCode=0:wait
    print  #inc.code,"!cls"
    open incFile$ for input as #fromFile
        print  #inc.code, "!contents #fromFile";
    close #fromFile
return

[cancelInclude]
    getInclude$=""
    goto [quitInclude]

[acceptInclude]
    getInclude$=includeFile$
[quitInclude]
     if includeCode=1 then close #inc
   includeCode=0
RETURN
