#!yab

doc Author: Jan Bungeroth
doc Thanks to: Genki, Lelldorin, lorglas, Stargater, DasJott, bbjimmy
doc (c) 2006-2017 in terms of the Artistic License

doc
doc The yab-IDE provides you with an integrated development suite for yab
doc Enjoy.
path()
versionnumber$="2.2.8"

settingsRCSOff = true
globalConfigDir$ = trim$(system$("finddir B_USER_SETTINGS_DIRECTORY"))+"/yab-ide/"

if(LoadSettings() = 1) then

	MAXFILES = 20
	DEBUG = true
	

	settingsYabDir$ = path$ //"/boot/apps/yab-1.7/"
	globalProjectDir$ = trim$(system$("finddir B_USER_DIRECTORY"))+"/yab_work/Programs/" 
	yabDir$ = yabpath$()
	ideDir$ = path$ //settingsYabDir$ + "yab-IDE/"
	
	buildDir$ = trim$(system$("finddir B_USER_DIRECTORY"))+"/yab_work/BuildFactory/" 
	globalHelpDir$ = settingsYabDir$ + "Documentation/"

	settingsLangUse = true
	settingsLangPath$ = "x-vnd.yab-IDE"

	settingsAutoIndent = true
	settingsAutoCompletion = true
	settingsACNumChar = 2
	settingsX = 50
	settingsY = 50
	settingsWidth = peek("desktopwidth")-100
	if(settingsWidth<600) settingsWidth = 600
	settingsHeight = peek("desktopheight")-100
	settingsFullScreen = false
	settingsFullEditor = false
	settingsVSplitDivider = 180
	settingsV2SplitDivider = 41
	settingsHSplitDivider = settingsHeight-240
	settingsCalcPatternX = 200
	settingsCalcPatternY = 150
	settingsColorSelectX = 100
	settingsColorSelectY = 100
	settingsColorSelectR = 255
	settingsColorSelectG = 255
	settingsColorSelectB = 255
	settingsAskForSaving = true
	settingsFindCS = false
	settingsOldSearch$ = ""
	settingsFindAlert = true
	settingsReformatAlert = true
	settingsReformatUndoAlert = true
	settingsTabSpaces = 4
	settingsFontFamily$ = "DejaVu Sans Mono"
	settingsFontStyle$ = "Book"
	settingsFontSize = 12
	globalRealFontSize = 15
	settingsYabParam$ = ""
	settingsProgParam$ = ""

	dim globalAllNames$(MAXFILES)
	dim globalTextFinder(MAXFILES)

	for i=1 to MAXFILES
		globalAllNames$(i) = ""
		globalTextFinder(i) = 0
	next i

endif


restartSettingsLangUse = settingsLangUse
textcolor_r = 0
textcolor_g = 0
textcolor_b = 0

// globalNoRCS = system("test -e /boot/beos/bin/ci") or system("test -e /boot/beos/bin/co") or system("test -e /boot/beos/bin/rlog") or settingsRCSOff
globalNoRCS = settingsRCSOff
globalCurrentText = 0
globalHSplitDivider = settingsHSplitDivider
globalReformatUndo = false
globalSelectErrorLines = true
globalNewNumber = 0
globalNumOpenFiles = 0
globalWasChanged = false
globalRealOS$ = upper$(system$("uname -o"))
globalRealOS$ = left$(globalRealOS$, 4)

oldSpinner = 1

if(settingsLangUse) then
	localize settingsLangPath$
endif


OpenMainWindow()
ActivateMenus(false)
UpdateStatusbar()

LoadOpenFiles()

if(settingsFullScreen) then
	menu set "View", "Full screen", "mark", "MainView"
	window set "MainView", "moveto", 0,0
	window set "MainView", "resizeto", peek("desktopwidth")-1, peek("desktopheight")-1
	window set "MainView", "MinimumTo", peek("desktopwidth")-1, peek("desktopheight")-1
	window set "MainView", "MaximumTo", peek("desktopwidth")-1, peek("desktopheight")-1
endif
if(settingsFullEditor) then
	oldSplitX = splitview get "VSplit", "Divider"
//	oldSplitY = splitview get "HSplit", "Divider"
	tmp = window get "MainView", "Height"
	splitview set "HSplit", "Divider", tmp-51
	splitview set "VSplit", "Divider", 0
	menu set "View", "Maximize editor", "mark", "MainView"
endif

dim msg$(1)
dim pattern(8,8)

inloop = true
while(inloop)
	sleep 0.01
	n = split(message$, msg$(), "|")
	for i = 1 to n
		if(DEBUG and msg$(i)<>"") print msg$(i)
		switch(msg$(i))
			case "ToolbarNew"
			case MyTranslate$("MainView:File:New...")
				foundEmpty = 0
				for j=1 to MAXFILES
					if(globalAllNames$(j) = "") then
						foundEmpty = j
						break
					endif
				next j
				if(not foundEmpty) then
					alert MyTranslate$("Sorry, you can not open more than ")+str$(MAXFILES)+MyTranslate$(" files at once!\n\nPlease close one or more other files first."), "Ok", "Warning"
				else
					NewDocument(foundEmpty)
					if(globalNumOpenFiles = 1) then
						ActivateMenus(true)
						splitview set "V2Split", "Divider", settingsV2SplitDivider
					endif
				endif
				break
			case "ToolbarOpen"
			case MyTranslate$("MainView:File:Open...")
				foundEmpty = 0
				for j=1 to MAXFILES
					if(globalAllNames$(j) = "") then
						foundEmpty = j
						break
					endif
				next j
				if(not foundEmpty) then
					alert MyTranslate$("Sorry, you can not open more than ")+str$(MAXFILES)+MyTranslate$(" files at once!\n\nPlease close one or more other files first."), "Ok", "Warning"
				else
					tmp$ = filepanel "Load-File", "Open", globalProjectDir$
					if(tmp$<>"") then
						foundProject = false
						for j = 1 to MAXFILES
							if(globalAllNames$(j) = tmp$) then
								alert "File is already open.", "Ok", "info"
								ActivateText(j)
								foundProject = true
								break
							endif
						next j
						if(foundProject) break

						handle = open(tmp$, "r")
						if(handle) then
							WaitWindow(tmp$)
							text$ = ""
							while(not eof(handle))
								t$ = GetLine$(handle)+"\n"
								if(len(t$)*8>4000) textedit set "Text"+str$(foundEmpty), "textwidth", len(t$)*8+8
								text$ = text$ + t$
							wend
							close(handle)
							globalCurrentText = foundEmpty
							textedit add "Text"+str$(globalCurrentText), text$
							textedit set "Text"+str$(globalCurrentText), "changed", false
							textedit set "Text"+str$(globalCurrentText), "gotoline", ReadLineFromAttr(tmp$)
							stackview set "Stack", globalCurrentText
							stackview set "Lines", globalCurrentText
							globalAllNames$(globalCurrentText) = tmp$
							t = columnbox count "FileBox" 
							columnbox add "FileBox", 1, t+1,20,"__Mime__=application/x-vnd.yab-app"
							columnbox add "FileBox", 2, t+1,20, GetFileName$(tmp$) //  "Filename", t, GetFileName$(tmp$)
							columnbox select "FileBox", t+1
							globalTextFinder(globalCurrentText) = t+1
							option set "Text"+str$(globalCurrentText), "focus", true
							oldScroll = -1
							globalNumOpenFiles = globalNumOpenFiles + 1
							if(globalNumOpenFiles = 1) then
								ActivateMenus(true)
								splitview set "V2Split", "Divider", settingsV2SplitDivider
							endif
							globalProjectDir$ = GetDirectory$(tmp$)
							window close "WaitWindow"
						else
							alert MyTranslate$("Error while loading file:\n\n")+tmp$, "Ok", "Stop"
						endif
					endif
				endif
				break
			case "ToolbarClose"
			case MyTranslate$("MainView:File:Close")
				if(textedit get "Text"+str$(globalCurrentText), "hasChanged") then
					tmpSave = alert MyTranslate$("File \"")+GetFileName$(globalAllNames$(globalCurrentText))+MyTranslate$("\" not saved!\n\nSave the file now?"), "Cancel", "Close", "Save", "warning"
					if(tmpSave = 1) break
					if(tmpSave = 3) then
						tmpSave = SaveCurrentFile()
						if(not tmpSave) break
					endif
				endif

				textedit clear "Text"+str$(globalCurrentText)
				globalAllNames$(globalCurrentText) = ""

				columnbox remove "FileBox", globalTextFinder(globalCurrentText)
				closeFinished = 0
				newCurrent = 0
				for tmpClose = 1 to MAXFILES
					if(globalTextFinder(tmpClose)>globalTextFinder(globalCurrentText)) then
						if(globalTextFinder(tmpClose) = globalTextFinder(globalCurrentText) + 1) then
							closeFinished = globalTextFinder(tmpClose) - 1
							newCurrent = tmpClose
						endif
						globalTextFinder(tmpClose) = globalTextFinder(tmpClose) - 1
					endif
				next tmpClose

				if(closeFinished=0) then
					closeFinished = globalTextFinder(globalCurrentText) - 1
					if(closeFinished = 0) then
						newCurrent = 0
					else
						for j = 1 to MAXFILES
							if(globalTextFinder(j) = globalTextFinder(globalCurrentText)-1) then
								newCurrent = j
								break
							endif
						next j
					endif
				endif

				globalTextFinder(globalCurrentText) = 0
				globalCurrentText = newCurrent

				if(closeFinished=0) then
					stackview set "Stack", MAXFILES+2
					stackview set "Lines", MAXFILES+2
					settingsV2SplitDivider = splitview get "V2Split", "Divider"
					splitview set "V2Split", "Divider", 0
					ActivateMenus(false)
				else
					ActivateText(globalCurrentText)
				endif
				globalNumOpenFiles = globalNumOpenFiles - 1
				break
			case "ToolbarSave"
			case MyTranslate$("MainView:File:Save")
				tmpNull = SaveCurrentFile()
				break
			case MyTranslate$("MainView:File:Save as...")
				tmpSaveAs$ = filepanel "Save-File", "Save", GetDirectory$(globalAllNames$(globalCurrentText)), GetFileName$(globalAllNames$(globalCurrentText))
				print tmpSaveAs$
				if(tmpSaveAs$<>"") then
					handle = open(tmpSaveAs$, "w")
					if(handle) then
						print #handle textedit get$ "Text"+str$(globalCurrentText);
						close(handle)
						tmpCurrentLine = textedit get "Text"+str$(globalCurrentText), "currentline"
						attribute set "Int", "linenumber", "tmpCurrentLine", tmpSaveAs$
						textedit set "Text"+str$(globalCurrentText), "changed", false
						globalAllNames$(globalCurrentText) = tmpSaveAs$
						columnbox clear "FileBox"
						for j=1 to MAXFILES
							for k=1 to MAXFILES
								if(globalTextFinder(j)=k) then
									t = columnbox count "FileBox"
									columnbox add "FileBox", 1, t+1,20, "__Mime__=application/x-vnd.yab-app"
									columnbox add "FileBox", 2, t+1,20, GetFileName$(globalAllNames$(j))
									break
								endif
							next k
						next j
						columnbox select "FileBox", globalTextFinder(globalCurrentText)
					else
						alert "File could not be saved!", "Ok", "warning"
					endif
				endif
				break
			case MyTranslate$("MainView:File:Save as template...")
				SaveAsTemplate()
				break
			case MyTranslate$("MainView:File:Export as HTML...")
				ExportAsHTML()
				break
			case MyTranslate$("MainView:File:Page setup...")
				printer setup globalConfigDir$+"printersetup"
				break
			case MyTranslate$("MainView:File:Print...")
				if(globalCurrentText>0) then
					err = printer globalAllNames$(globalCurrentText), globalConfigDir$+"printersetup", "Text"+str$(globalCurrentText)
					if(err = 4) then
						printer setup "/tmp/printersetup"
						err = printer globalAllNames$(globalCurrentText), "/tmp/printersetup", "Text"+str$(globalCurrentText)
						system("rm -f /tmp/printersetup >/dev/null")
					endif
					if(err>1 and err<5) then
						alert "Error while printing!", "Ok", "warning"
					endif
				endif
				break
			case "_QuitRequested"
				// TODO make backups and save open files
				inloop = false
				if(not settingsFullScreen) then
					settingsX = window get "MainView", "Position-X"
					settingsY = window get "MainView", "Position-Y"
					settingsWidth = window get "MainView", "Width"
					settingsHeight = window get "MainView", "Height"
				endif
				if(not settingsFullEditor) then
					settingsVSplitDivider = splitview get "VSplit", "Divider"
					settingsV2SplitDivider = splitview get "V2Split", "Divider"
					settingsHSplitDivider = splitview get "HSplit", "Divider"
				endif
				break
			case "MainView:_QuitRequested"
			case MyTranslate$("MainView:File:Quit")
				tmpSelect = 1
				if(globalCurrentText>0) then
					for j=1 to MAXFILES
						if(textedit get "Text"+str$(j), "hasChanged") then
							tmpSelect = alert "Some files are not saved!\n\nDo you really want to quit?", "Quit", "Cancel", "",  "warning"
							break
						endif
					next j
				endif
				if(tmpSelect = 1) then
					inloop = false
					if(not settingsFullScreen) then
						settingsX = window get "MainView", "Position-X"
						settingsY = window get "MainView", "Position-Y"
						settingsWidth = window get "MainView", "Width"
						settingsHeight = window get "MainView", "Height"
					endif
					if(not settingsFullEditor) then
						settingsVSplitDivider = splitview get "VSplit", "Divider"
						settingsV2SplitDivider = splitview get "V2Split", "Divider"
						settingsHSplitDivider = splitview get "HSplit", "Divider"
					endif
				endif
				break
			case "ToolbarCut"
			case MyTranslate$("MainView:Edit:Cut")
				textedit set "Text"+str$(globalCurrentText), "Cut"
				break
			case "ToolbarCopy"
			case MyTranslate$("MainView:Edit:Copy")
				if(globalIsHelp) then
					textedit set "Text"+str$(MAXFILES+1), "Copy"
				else
					textedit set "Text"+str$(globalCurrentText), "Copy"
				endif
				break
			case "ToolbarPaste"
			case MyTranslate$("MainView:Edit:Paste")
				textedit set "Text"+str$(globalCurrentText), "Paste"
				break
			case "ToolbarUndo"
			case MyTranslate$("MainView:Edit:Undo")
				textedit set "Text"+str$(globalCurrentText), "Undo"
				break
			case MyTranslate$("MainView:Edit:Select all")
				if(globalIsHelp) then
					textedit set "Text"+str$(MAXFILES+1), "Select-All"
				else
					textedit set "Text"+str$(globalCurrentText), "Select-All"
				endif
				break
			case MyTranslate$("MainView:Edit:Clear")
				textedit set "Text"+str$(globalCurrentText), "Clear"
				break
			case MyTranslate$("MainView:Edit:Find")
				option set "ToolbarText", "focus", true
				break
			case MyTranslate$("MainView:Edit:Find again")
				if(settingsOldSearch$<>"") then
					if(settingsFindCS) then
						searchLineNum = textedit get "Text"+str$(globalCurrentText), "Case-Sensitive-Find", settingsOldSearch$ 
					else
						searchLineNum = textedit get "Text"+str$(globalCurrentText), "Find", settingsOldSearch$ 
					endif
					option set "Text"+str$(globalCurrentText), "Focus", true
				endif
				break
			case MyTranslate$("MainView:Edit:Find and replace")
				if(settingsFullEditor) then
					splitview set "VSplit", "Divider", oldSplitX
					splitview set "HSplit", "Divider", oldSplitY
					menu set "View", "Maximize editor", "plain", "MainView"
					settingsFullEditor = false
				endif
				tabview set "HTab", 3
				option set "FindTCFind", "Focus", true
				break
			case "ToolbarRun"
			case MyTranslate$("MainView:Program:Run")
				isNotSaved = textedit get "Text"+str$(globalCurrentText), "hasChanged"
				askForSaving = 3
				if(settingsAskForSaving and isNotSaved) then 
					askForSaving = alert "Program is not saved.\n\nSave it now?", "Cancel", "Save Always", "Save Now", "info"
				endif

				if(askForSaving>1) then
					if(askForSaving = 2) settingsAskForSaving = true
					if(isNotSaved) then
						tmpSave = SaveCurrentFile()
						if(not tmpSave) break
					endif
					RunProgram(globalAllNames$(globalCurrentText))
				endif
				break
			case "ToolbarRunTerm"
			case MyTranslate$("MainView:Program:Run in Terminal")
				isNotSaved = textedit get "Text"+str$(globalCurrentText), "hasChanged"
				askForSaving = 3
				if(settingsAskForSaving and isNotSaved) then 
					askForSaving = alert "Program is not saved.\n\nSave it now?", "Cancel", "Save Always", "Save Now", "info"
				endif

				if(askForSaving>1) then
					if(askForSaving = 2) settingsAskForSaving = true
					if(isNotSaved) then
						tmpSave = SaveCurrentFile()
						if(not tmpSave) break
					endif
					RunInTerminal(globalAllNames$(globalCurrentText))
				endif
				break
			case MyTranslate$("MainView:Program:Set run parameters...")
				SetRunParameters()
				break
			case "ToolbarBuild"
			case MyTranslate$("MainView:Program:Build Factory...")
				isNotSaved = textedit get "Text"+str$(globalCurrentText), "hasChanged"
				askForSaving = 3
				if(settingsAskForSaving and isNotSaved) then 
					askForSaving = alert "Program is not saved.\n\nSave it now?", "Cancel", "Save Always", "Save Now", "info"
				endif

				if(askForSaving>1) then
					if(askForSaving = 2) settingsAskForSaving = true
					if(isNotSaved) then
						tmpSave = SaveCurrentFile()
						if(not tmpSave) break
					endif
					Building()
				endif
				break
			case MyTranslate$("MainView:Program:Open project folder...")
				OpenProjectDir$ = getprojectdir$()
				
				//system("open " +  globalProjectDir$)
				system("open " +  OpenProjectDir$)
				break
			case "ToolbarPattern"
			case MyTranslate$("MainView:Tools:Pattern editor...")
				OpenCalcPattern(settingsCalcPatternX,settingsCalcPatternY)
				break
			case MyTranslate$("MainView:Tools:Color selection...")
				OpenColorSelection(settingsColorSelectX,settingsColorSelectY, settingsColorSelectR, settingsColorSelectG, settingsColorSelectB)
				break
			case MyTranslate$("MainView:Tools:ASCII table...")
				AsciiWindow()
				break
			case MyTranslate$("MainView:View:Next file")
				findNext = false
				tmpCounter = globalCurrentText
				while(not findNext)
					tmpCounter = tmpCounter + 1
					if(tmpCounter>MAXFILES) tmpCounter = 1
					if(tmpCounter = globalCurrentText) then
						findNext = true
					else
						if(globalAllNames$(tmpCounter)<>"") then
							globalCurrentText = tmpCounter
							ActivateText(globalCurrentText)
							findNext = true
						endif
					endif
				wend
				break
			case MyTranslate$("MainView:View:Previous file")
				findNext = false
				tmpCounter = globalCurrentText
				while(not findNext)
					tmpCounter = tmpCounter - 1
					if(tmpCounter=0) tmpCounter = MAXFILES
					if(tmpCounter = globalCurrentText) then
						findNext = true
					else
						if(globalAllNames$(tmpCounter)<>"") then
							globalCurrentText = tmpCounter
							ActivateText(globalCurrentText)
							findNext = true
						endif
					endif
				wend
				break
			case MyTranslate$("MainView:View:Full screen")
				if settingsFullScreen then
					menu set "View", "Full screen", "plain", "MainView"
					currentDivider = peek("desktopheight")-1 - splitview get "HSplit", "Divider"
					window set "MainView", "moveto", settingsX,settingsY
					window set "MainView", "MinimumTo", 600,300
					window set "MainView", "MaximumTo", 2000, 2000
					window set "MainView", "resizeto", settingsWidth, settingsHeight
					splitview set "HSplit", "Divider", settingsHeight-currentDivider 
					settingsFullScreen = false
				else
					settingsX = window get "MainView", "Position-X"
					settingsY = window get "MainView", "Position-Y"
					settingsWidth = window get "MainView", "Width"
					settingsHeight = window get "MainView", "Height"
					currentDivider = settingsHeight - splitview get "HSplit", "Divider"
					menu set "View", "Full screen", "mark", "MainView"
					window set "MainView", "moveto", 0,0
					window set "MainView", "resizeto", peek("desktopwidth")-1, peek("desktopheight")-1
					window set "MainView", "MinimumTo", peek("desktopwidth")-1, peek("desktopheight")-1
					window set "MainView", "MaximumTo", peek("desktopwidth")-1, peek("desktopheight")-1
					splitview set "HSplit", "Divider", peek("desktopheight")-1-currentDivider 
					settingsFullScreen = true
				endif
				break
			case MyTranslate$("MainView:View:Maximize editor")
				if(settingsFullEditor) then
					splitview set "VSplit", "Divider", oldSplitX
					splitview set "HSplit", "Divider", oldSplitY
					menu set "View", "Maximize editor", "plain", "MainView"
					settingsFullEditor = false
				else
					oldSplitX = splitview get "VSplit", "Divider"
					oldSplitY = splitview get "HSplit", "Divider"
					tmp = window get "MainView", "Height"
					splitview set "HSplit", "Divider", tmp-51
					splitview set "VSplit", "Divider", 0
					menu set "View", "Maximize editor", "mark", "MainView"
					settingsFullEditor = true
				endif
				break
			case MyTranslate$("MainView:View:Auto indent")
				if(settingsAutoIndent) then
					menu set "View", "Auto indent", "plain", "MainView"
				else
					menu set "View", "Auto indent", "mark", "MainView"
				endif
				settingsAutoIndent = not settingsAutoIndent
				for tmpAllFiles = 1 to MAXFILES
					textedit set "Text"+str$(tmpAllFiles), "autoindent", settingsAutoIndent
				next tmpAllFiles
				break
			case MyTranslate$("MainView:View:Auto completion")
                                if(settingsAutoCompletion) then
                                        menu set "View", "Auto completion", "plain", "MainView"
                                else
                                        menu set "View", "Auto completion", "mark", "MainView"
                                endif
                                settingsAutoCompletion = not settingsAutoCompletion
                                for tmpAllFiles = 1 to MAXFILES
                                        textedit set "Text"+str$(tmpAllFiles), "has-autocompletion", settingsAutoCompletion
                                next tmpAllFiles
                                break 
			case MyTranslate$("MainView:View:Reformat sourcecode")
				reformatUndo$ = textedit get$ "Text"+str$(globalCurrentText)
				globalReformatUndo = true
				menu set "View", "Undo reformat", "enable", "MainView"
				textedit clear "Text"+str$(globalCurrentText)
				//tmp$ = ReformatSource$(reformatUndo$)
				textedit add "Text"+str$(globalCurrentText),ReformatSource$(reformatUndo$) 
				if(ReformatError(false,0)<>0 and settingsReformatAlert) then
					tmp = alert "Reformating did not close all open loops and conditions.\nReformating currently does not support loops and conditions opened and closed by a colon (:).\nE.g. while(loop):wend\n\nYou can undo the reformating before doing any further changes.", "Do not show this warning again", "Ok" , "", "warning"
					if(tmp = 1) settingsReformatAlert = false
				endif
				break
			case MyTranslate$("MainView:View:Undo reformat")
				tmp = alert "Changes made since reformating will be lost!", "Cancel", "Do not show this warning again", "Undo reformating", "warning"
				if(tmp > 1) then
					if(tmp=2) settingsReformatUndoAlert = false
					globalReformatUndo = false
					textedit clear "Text"+str$(globalCurrentText)
					textedit add "Text"+str$(globalCurrentText), reformatUndo$
					menu set "View", "Undo reformat", "disable", "MainView"
				endif
				break
			case MyTranslate$("MainView:View:Refresh colors")
				textedit color "Text"+str$(globalCurrentText), "textcolor", textcolor_r, textcolor_g, textcolor_b
				break
			case "ToolbarOptions"
			case MyTranslate$("MainView:View:Options...")
				OptionWindow()
				break
                        case "ToolbarHelp"
                        case MyTranslate$("MainView:Help:Short command help...")
                                system("open "+globalHelpDir$+"yab-Commands &")
                                break
                        case MyTranslate$("MainView:Help:Yabasic manual...")
                                system("open "+globalHelpDir$+"yabasic.html &")
                                break 
			case MyTranslate$("MainView:Help:Online resources:German BeUsergroup...")
                                system("open http://www.beusergroup.de &")
                                break 
			case MyTranslate$("MainView:Help:Online resources:BeSly database...")
                                system("open http://www.besly.de &")
                                break 
			case MyTranslate$("MainView:Help:Online resources:Yabasic homepage...")
                                system("open http://www.yabasic.de &")
                                break 
			case MyTranslate$("MainView:Help:Online resources:Yab homepage...")
                                system("open http://yab.orgfree.com &")
                                break 
			case MyTranslate$("MainView:Help:Online resources:Yab forum...")
                                system("open http://yab.orgfree.com/forum/ &")
                                break 
            case MyTranslate$("MainView:Help:Online resources:Team Maui...")
                                system("open http://www.team-maui.org &")
                                break                     
			case MyTranslate$("MainView:Help:About...")
				AboutWindow()
				break
				
			// the find and replace tabview
			case "FindCS:ON"
			case "FindCS:OFF"
				settingsFindCS = not settingsFindCS
				break
			case "FindFind"
				settingsOldSearch$ = textcontrol get$ "FindTCFind"
				if(settingsOldSearch$<>"") then
					if(settingsFindCS) then
						searchLineNum = textedit get "Text"+str$(globalCurrentText), "Case-Sensitive-Find", settingsOldSearch$ 
					else
						searchLineNum = textedit get "Text"+str$(globalCurrentText), "Find", settingsOldSearch$ 
					endif
					option set "Text"+str$(globalCurrentText), "Focus", true
				endif
				break
			case "FindReplace"
				settingsOldSearch$ = textcontrol get$ "FindTCFind"
				if(settingsOldSearch$<>"") then
					if(settingsFindCS) then
						searchLineNum = textedit get "Text"+str$(globalCurrentText), "Case-Sensitive-Find", settingsOldSearch$ 
					else
						searchLineNum = textedit get "Text"+str$(globalCurrentText), "Find", settingsOldSearch$ 
					endif
					if(searchLineNum <> -1) then
					changestring()	
						
					endif
					option set "Text"+str$(globalCurrentText), "Focus", true					
				endif
				break
			case "FindReplAll"
				if(settingsFindAlert) then
					tmpAlert = alert "The operation \"Replace All\" can not be reverted!\n\nDo you want to continue?", "Cancel", "Do not show this warning again", "Ok", "warning"
					if(tmpAlert = 1) break
					if(tmpAlert = 2) settingsFindAlert = false
				endif
				settingsOldSearch$ = textcontrol get$ "FindTCFind"
				if(settingsOldSearch$<>"") then
					searchLineNum = 0
					while(searchLineNum<>-1)
						if(settingsFindCS) then
							searchLineNum = textedit get "Text"+str$(globalCurrentText), "Case-Sensitive-Find", settingsOldSearch$ 
						else
							searchLineNum = textedit get "Text"+str$(globalCurrentText), "Find", settingsOldSearch$ 
						endif
						if(searchLineNum <> -1) then
							changestring()
						endif
					wend
					option set "Text"+str$(globalCurrentText), "Focus", true					
				endif
				break

			// the immediate tabview
			case "ImmediateExecute"
				tmp$ = textcontrol get$ "ImmediateInput"
				ImmediateExec(tmp$)
				break

		end switch

		// the output listbox, handle error messages
		if((left$(msg$(i),22) = "YabOutputList:_Select:") or (left$(msg$(i),22) = "YabOutputList:_Invoke:")) then
			tmp$ = listbox get$ "YabOutputList", val(right$(msg$(i),len(msg$(i))-22))
			if(left$(tmp$,8) = "---Error") then
				num = instr(tmp$, "line ")
				if(num) then
					num = num + 5
					number$ = ""
					repeat
						number$ = number$ + mid$(tmp$,num,1)
						num = num + 1
					until (mid$(tmp$,num,1) = ":")
					num = val(number$)

					errorFileName$ = globalAllNames$(globalCurrentText)
					errorFileFound = false
					rightBound = instr(tmp$, ".yab")
					if(rightBound) then
						errorFileName$ = mid$(tmp$, 13, rightBound-13+4)
					endif
					if(errorFileName$<>globalAllNames$(globalCurrentText)) then
						// check whether library is loaded already...
						for tmpCheckName = 1 to MAXFILES
							if((left$(errorFileName$,1) = "/" and errorFileName$ = globalAllNames$(tmpCheckName)) or (left$(errorFileName$,1) <> "/" and right$(globalAllNames$(tmpCheckName),len(errorFileName$)) = errorFileName$)) then
								ActivateText(tmpCheckName)
								errorFileFound = true
								break
							endif
						next tmpCheckName
						// otherwise load it now
					else
						errorFileFound = true
					endif

					if(errorFileFound) then
						textedit set "Text"+str$(globalCurrentText),"gotoline", num+7
						textedit set "Text"+str$(globalCurrentText),"gotoline", num
						textedit set "Text"+str$(globalCurrentText),"select", num
						if(globalSelectErrorLines) option set "Text"+str$(globalCurrentText),"focus", true
					endif
				endif
			endif
		endif
			

		// the search field in the toolbar
		if(left$(msg$(i),12) = "ToolbarText:" or msg$(i) = "ToolbarFind") then
			if(msg$(i) = "ToolbarFind") then
				settingsOldSearch$ = textcontrol get$ "ToolbarText"
			else
				settingsOldSearch$ = right$(msg$(i), len(msg$(i))-12)
			endif
			if(settingsFindCS) then
				searchLineNum = textedit get "Text"+str$(globalCurrentText), "Case-Sensitive-Find", settingsOldSearch$ 
			else
				searchLineNum = textedit get "Text"+str$(globalCurrentText), "Find", settingsOldSearch$ 
			endif
			if(DEBUG) print searchLineNum
			option set "Text"+str$(globalCurrentText), "Focus", true
		endif

		// the find and replace tabview
		// if(left$(msg$(i),11) = "FindTCFind:" and ) then
		// 	option set "FindTCReplace", "focus", true
		// endif
		// if(left$(msg$(i),14) = "FindTCReplace:") then
			// option set "FindFind", "focus", true
		// endif


		// the immediate tabview
		if(left$(msg$(i),15) = "ImmediateInput:") then
			ImmediateExec(right$(msg$(i), len(msg$(i))-15))
		endif

		// the project columnbox
		if(left$(msg$(i),15) = "FileBox:_Select") then
			tmp$ = right$(msg$(i),len(msg$(i))-16)
			for tmpFiles = 1 to MAXFILES // arraysize(globalTextFinder(),1)
				if(DEBUG) print val(tmp$), globalTextFinder(tmpFiles)
				if(globalTextFinder(tmpFiles)=val(tmp$)) then
					ActivateText(tmpFiles)
					break
				endif
			next tmpFiles
		endif

		// something dropped on the textedit
		if(left$(msg$(i),18) = "V2Split2:_Dropped:" and globalCurrentText<>0) then
			tmp$ = right$(msg$(i),len(msg$(i))-18)
			handle = open(tmp$, "r")
			if(handle) then
				WaitWindow(tmp$)
				text$ = ""
				while(not eof(handle))
					text$ = text$ + GetLine$(handle)+"\n"
				wend
				close(handle)
				tmp = textedit get "Text"+str$(globalCurrentText), "currentline"
				textedit add "Text"+str$(globalCurrentText), left$(text$,len(text$)-1)
				textedit set "Text"+str$(globalCurrentText), "changed", true
				textedit set "Text"+str$(globalCurrentText), "gotoline", tmp
				option set "Text"+str$(globalCurrentText), "focus", true
				oldScroll = -1
				window close "WaitWindow"
			else
				alert MyTranslate$("Error while loading file:\n\n")+tmp$, "Ok", "warning"
			endif
		endif

		// something dropped on the project columnbox
		if(left$(msg$(i),17) = "VSplit1:_Dropped:") then
			foundEmpty = 0
			for j=1 to MAXFILES
				if(globalAllNames$(j) = "") then
					foundEmpty = j
					break
				endif
			next j
			if(not foundEmpty) then
				alert MyTranslate$("Sorry, you can not open more than ")+str$(MAXFILES)+MyTranslate$(" files at once!\n\nPlease close one or more other files first."), "Ok", "Warning"
			else
				tmp$ = right$(msg$(i),len(msg$(i))-17)
				foundProject = false
				for j = 1 to MAXFILES
					if(globalAllNames$(j) = tmp$) then
						alert "File is already open.", "Ok", "info"
						ActivateText(j)
						foundProject = true
						break
					endif
				next j
				if(not foundProject) then
					handle = open(tmp$, "r")
					if(handle) then
						WaitWindow(tmp$)
						text$ = ""
						while(not eof(handle))
							text$ = text$ + GetLine$(handle)+"\n"
						wend
						close(handle)
						globalCurrentText = foundEmpty
						textedit add "Text"+str$(globalCurrentText), left$(text$,len(text$)-1)
						textedit set "Text"+str$(globalCurrentText), "changed", false
						textedit set "Text"+str$(globalCurrentText), "gotoline", ReadLineFromAttr(tmp$)
						stackview set "Stack", globalCurrentText
						stackview set "Lines", globalCurrentText
						globalAllNames$(globalCurrentText) = tmp$
						option set "Text"+str$(globalCurrentText), "focus", true
						oldScroll = -1
						window close "WaitWindow"
					else
						alert MyTranslate$("Error while loading file:\n\n")+tmp$, "Ok", "Stop"
					endif
				endif
			endif
		endif

		// help selected
		if(left$(msg$(i),9) = "HelpTree:") then
			//tmp$ = right$(msg$(i), len(msg$(i))-17)
			tmp=treebox get "HelpTree"
			treebox select "HelpTree", tmp
			tmp$ = treebox get$ "HelpTree", tmp
			t$ = SyntaxGetInfoText$(ideDir$+"data/Help_En.dat", ideDir$+"data/Help_En_Index.dat", tmp$)
			if(t$<>"") then
				textedit clear "Text"+str$(MAXFILES+1)
				textedit add "Text"+str$(MAXFILES+1), t$
			endif
		endif 

		// search help
		if(left$(msg$(i),9) = "HelpFind:") then
			tmp$ = right$(msg$(i), len(msg$(i))-9)
			tmp$ = trim$(tmp$)
			tmp$ = lower$(tmp$)
			t$ = SyntaxGetInfoText$(ideDir$+"data/Help_En.dat", ideDir$+"data/Help_En_Index.dat", tmp$)
			if(t$<>"") then
				textedit clear "Text"+str$(MAXFILES+1)
				textedit add "Text"+str$(MAXFILES+1), t$
			endif
		endif
	next i

	if(globalCurrentText>0 and not globalWasChanged and textedit get "Text"+str$(globalCurrentText), "hasChanged") then
		globalWasChanged = true
		columnbox add "FileBox", 1, globalTextFinder(globalCurrentText), 20, "__Mime__=application/x-vnd.yab-app"
	endif

	UpdateStatusbar()

	if(settingsFullEditor) then
		tmp = window get "MainView", "Height" - 74
		if(splitview get "VSplit", "Divider" <> 0 or splitview get "HSplit", "Divider" <> tmp) then
			settingsFullEditor = false
			menu set "View", "Maximize editor", "plain", "MainView"
		endif
	endif

	if(globalCurrentText > 0) then
		// Update the line numbers
		// we are cheeting a bit :), we calculate the numbers for a 1200-pixel high view
		scroll = textedit get "Text"+str$(globalCurrentText), "vertical-scrollbar"
		v2Split = splitview get "V2Split", "divider"
		if(scroll<>oldScroll or v2Split<>oldV2Split) then
			scrollLine = int(scroll/globalRealFontSize)
			scrollPos = mod(scroll,globalRealFontSize)
			UpdateLines(scrollPos, 1200, scrollLine, globalRealFontSize)
			oldScroll = scroll
			oldV2Split = v2Split
			// scrollLine = int((scroll+2)/15)+1
			// scrollPos = mod((globalHSplitDivider-1-peek("scrollbarwidth")+scroll),15)+5
			// scrollPos = mod((1000+scroll),15)+5
			// UpdateLines(scrollPos, globalHSplitDivider-1-peek("scrollbarwidth"), scrollLine, 15)
			// UpdateLines(scrollPos, 1200, scrollLine, 15)
			// oldScroll = scroll
		endif

		// Check the spincontrol
		spinner = spincontrol get "ToolbarGotoLine"
		if(spinner <> oldSpinner) then
			textedit set "Text"+str$(globalCurrentText), "gotoline", spinner
			textedit set "Text"+str$(globalCurrentText), "select", 0
			textedit set "Text"+str$(globalCurrentText), "select", spinner
			option set "Text"+str$(globalCurrentText), "Focus", true
			oldSpinner = spinner
		endif
	endif

	// switch tabs from help to files and vice versa
	if(globalIsHelp and tabview get "Tree" = 1) then
		globalIsHelp = false
		splitview set "V2Split", "divider", helpOldV2Split
		if(globalCurrentText>0) then
			ActivateHelpMenus(1)
			stackview set "Stack", globalCurrentText
			stackview set "Lines", globalCurrentText
		else
			ActivateHelpMenus(0)
			stackview set "Stack", MAXFILES+2
			stackview set "Lines", MAXFILES+2
		endif
	endif
	if(not globalIsHelp and tabview get "Tree" = 2) then
		ActivateHelpMenus(-1)
		globalIsHelp = true
		stackview set "Stack", MAXFILES+1
		stackview set "Lines", MAXFILES+1
		helpOldV2Split = splitview get "V2Split", "divider"
		splitview set "V2Split", "divider", 0
	endif
wend

window close "MainView"
SaveSettings()

// Open main window with everything
sub OpenMainWindow()
	local vsplitheight, hsplitheight, tabwidth, i, handle
	local tmp$
	local err, x, y

	x = peek("desktopwidth")
	y = peek("desktopheight")

	// open initialize the main window
	window open settingsX-3000,settingsY-3000 to settingsX+settingsWidth-3000,settingsY+settingsHeight-3000, "MainView", "yab-IDE"

	window open x/2-250-3000, y/2-200-3000 to x/2+249-3000,y/2+199-3000, "Splash", ""
	window set "Splash", "look", "bordered"
	err = draw image 0,0, ideDir$+"img/Splash.png", "Splash"
	draw set "HighColor", 56,61,127, "Splash" 
	draw set "DejaVu Sans Mono,Bold,18", "Splash"
	draw text 30, 280, "Version "+versionnumber$, "Splash"
	window set "Splash", "moveto", x/2-250,y/2-200
	set_up_BuildFactory()
	if(err>0) window close "Splash"
	
	
	
	window set "MainView", "look", "document"
	window set "MainView", "MinimumTo", 600,300

	// set all menus
	menu "File", "New...", "N", "MainView"
	menu "File", "Open...", "O", "MainView"
	menu "File", "Close", "W", "MainView"
	menu "File", "--", "", "MainView"
	menu "File", "Save", "S", "MainView"
	menu "File", "Save as...", "", "MainView"
	menu "File", "Save as template...", "", "MainView"
	menu "File", "Export as HTML...", "", "MainView"

	menu "File", "--", "", "MainView"
	menu "File", "Page setup...", "", "MainView"
	menu "File", "Print...", "P", "MainView"
	menu "File", "--", "", "MainView"
	menu "File", "Quit", "Q", "MainView"
	
	menu "Edit", "Undo", "Z", "MainView"
	menu "Edit", "--", "", "MainView"
	menu "Edit", "Cut", "X", "MainView"
	menu "Edit", "Copy", "C", "MainView"
	menu "Edit", "Paste", "V", "MainView"
	menu "Edit", "--", "", "MainView"
	menu "Edit", "Select all", "A", "MainView"
	menu "Edit", "--", "", "MainView"
	menu "Edit", "Find", "F", "MainView"
	menu "Edit", "Find again", "G", "MainView"
	menu "Edit", "Find and replace", "E", "MainView"

	menu "Program", "Run", "R", "MainView"
	menu "Program", "Run in Terminal", "T", "MainView"
	menu "Program", "--", "", "MainView"
	menu "Program", "Set run parameters...", "SR", "MainView"
	menu "Program", "--", "", "MainView"
	menu "Program", "Build Factory...", "B", "MainView"
	menu "Program", "--", "", "MainView"
	menu "Program", "Open project folder...", "SO", "MainView"

	if(not globalNoRCS) then
		menu "RCS", "Check In", "CI", "MainView"
		menu "RCS", "Check Out", "CO", "MainView"
		menu "RCS", "--", "", "MainView"
		menu "RCS", "Version History...", "CV", "MainView"
	endif
	
	menu "Tools", "Pattern editor...", "CP", "MainView"
	menu "Tools", "Color selection...", "CC", "MainView"
	menu "Tools", "--", "", "MainView"
	menu "Tools", "ASCII table...", "CA", "MainView"

	menu "View", "Next file", ".", "MainView"
	menu "View", "Previous file", ",", "MainView"
	menu "View", "--", "", "MainView"
	menu "View", "Full screen", "CF", "MainView"
	menu "View", "Maximize editor", "CE", "MainView"
	menu "View", "--", "", "MainView"
	menu "View", "Auto indent", "", "MainView"
	menu "View", "Auto completion", "", "MainView"
	menu "View", "Refresh colors", "", "MainView"
	menu "View", "--", "", "MainView"
	menu "View", "Reformat sourcecode", "CR", "MainView"
	menu "View", "Undo reformat", "", "MainView"
	menu "View", "--", "", "MainView"
	menu "View", "Options...", "", "MainView"
	if settingsFullScreen menu set "View", "Full screen", "mark", "MainView"
	if settingsFullEditor menu set "View", "Maximize editor", "mark", "MainView"
	if settingsAutoIndent menu set "View", "Auto indent", "mark", "MainView"
	if settingsAutoCompletion menu set "View", "Auto completion", "mark", "MainView"
	menu set "View", "Undo reformat", "disable", "MainView"

	menu "Help", "Short command help...", "H", "MainView"
	menu "Help", "Yabasic manual...", "M", "MainView"
	menu "Help", "--", "", "MainView"
	menu "Help", "Online resources", "", "MainView"
	submenu "Help", "Online resources", "BeSly database...", "", "MainView"
	submenu "Help", "Online resources", "German BeUsergroup...", "", "MainView"
	submenu "Help", "Online resources", "Team Maui...", "", "MainView"
	submenu "Help", "Online resources", "Yab homepage...", "", "MainView"
	submenu "Help", "Online resources", "Yab forum...", "", "MainView"
	submenu "Help", "Online resources", "Yabasic homepage...", "", "MainView"
	
	

	menu "Help", "--", "", "MainView"
	menu "Help", "About...", "", "MainView"

	// set the toolbar
	ToolbarCreate(0,peek("menuheight")+1,2000, "Toolbar", ideDir$+"img/", "MainView")
	ToolbarAddIcon("ToolbarNew", "New", "newp.png", "newn.png", "newd.png")
	ToolbarAddIcon("ToolbarOpen", "Open", "openp.png", "openn.png", "opend.png")
	ToolbarAddIcon("ToolbarSave", "Save", "savep.png", "saven.png", "saved.png")
	ToolbarAddIcon("ToolbarClose", "Close", "closep.png", "closen.png", "closed.png")
	ToolbarAddSeparator()
	ToolbarAddIcon("ToolbarCut", "Cut", "cutp.png", "cutn.png", "cutd.png")
	ToolbarAddIcon("ToolbarCopy", "Copy", "copyp.png", "copyn.png", "copyd.png")
	ToolbarAddIcon("ToolbarPaste", "Paste", "pastep.png", "pasten.png", "pasted.png")
	ToolbarAddIcon("ToolbarUndo", "Undo", "undop.png", "undon.png", "undod.png")
	// ToolbarAddIcon("ToolbarFind", "Find", "searchp.png", "searchn.png", "searchd.png")
	ToolbarAddSeparator()
	ToolbarAddIcon("ToolbarRun", "Run", "runp.png", "runn.png", "rund.png")
	ToolbarAddIcon("ToolbarRunTerm", "Run in Terminal", "runtermp.png", "runtermn.png", "runtermd.png")
	// ToolbarAddIcon("ToolbarDebug", "Debugger", "debugp.png", "debugn.png", "debugd.png")
	ToolbarAddIcon("ToolbarBuild", "Build Factory", "bindp.png", "bindn.png", "bindd.png")
	// ToolbarAddSeparator()
	// ToolbarAddIcon("ToolbarGui", "GUI Designer", "guip.png", "guin.png", "guid.png")
	ToolbarAddSeparator()
	ToolbarAddIcon("ToolbarPattern", "Pattern editor", "patternp.png", "patternn.png", "patternd.png")
	ToolbarAddIcon("ToolbarOptions", "Options", "optionsp.png", "optionsn.png", "optionsd.png")
	ToolbarAddIcon("ToolbarHelp", "yab Help", "helpp.png", "helpn.png", "helpd.png")
	ToolbarAddSeparator()

	spincontrol 383,2, "ToolbarGotoLine", "Go to Line:", 1, 100000, 1, "Toolbar"
	tooltip "ToolbarGotoLine", "Go to Line"
	draw set "highcolor", 185,185,185, "Toolbar"
	draw line 430,5 to 400,25, "Toolbar"
	draw set "highcolor", 239,239,239, "Toolbar"
	draw line 431,5 to 401,25, "Toolbar"

	button image 538,7, "ToolbarFind", ideDir$+"img/searchp.png", ideDir$+"img/searchn.png", ideDir$+"img/searchd.png", "Toolbar"
	tooltip "ToolbarFind", "Find"
	textcontrol 553,5 to 640,25, "ToolbarText", "", settingsOldSearch$, "Toolbar"
	draw set "highcolor", 185,185,185, "Toolbar"
	draw line 510,5 to 480,25, "Toolbar"
	draw set "highcolor", 239,239,239, "Toolbar"
	draw line 511,5 to 481,25, "Toolbar"

	// layout "top, left, right", "Toolbar"
	draw set "highcolor", 200,200,200, "Toolbar"
	draw line 0,29 to 2000,29, "Toolbar"
	draw set "highcolor", 184,184,184, "Toolbar"
	draw line 0,30 to 2000,30, "Toolbar"
	draw set "highcolor", 239,239,239, "Toolbar"
	draw line 0,31 to 2000,31, "Toolbar"


	// vertical splitview
	layout "standard", "MainView"
	splitview 0,peek("menuheight")+31, settingsWidth,settingsHeight-peek("scrollbarwidth"), "VSplit", true, true, "MainView"
	splitview set "VSplit", "Divider", settingsVSplitDivider
	splitview set "VSplit", "MinimumSizes", 0,400

	// horizontal splitview
	splitview 0,0, settingsWidth-settingsVSplitDivider,settingsHeight-peek("scrollbarwidth")+1, "HSplit", false, true, "VSplit2"
	splitview set "HSplit", "Divider", settingsHSplitDivider
	splitview set "HSplit", "MinimumSizes", 100,51

	splitview 0,0, settingsWidth-settingsVSplitDivider,settingsHSplitDivider-1, "V2Split", true,false, "HSplit1"
	splitview set "V2Split", "Divider", 0
	splitview set "V2Split", "MinimumSizes", 0,300


	vsplitheight = settingsHeight - peek("menuheight")-peek("scrollbarwidth")

	// tabview and treeboxes in the left vertical splitview
	tabview 0,1 to settingsVSplitDivider-1,vsplitheight-32, "Tree", "bottom", "VSplit1"
	tabview add "Tree", " Files "
	tabview add "Tree", " Help "
	columnbox 0,0 to settingsVSplitDivider-10,vsplitheight-42-peek("tabheight"), "FileBox", false, "no-border, resizable", "Tree1"
	columnbox column "FileBox", " ", 1, 20, 20, 20, "align-center"
	columnbox column "FileBox", "Filename",2, 300, 32, settingsVSplitDivider-32, "align-left"
	columnbox color "FileBox", "Selection-Active", 220,220,250 
	columnbox color "FileBox", "Row-Divider", 255,255,255 

	treebox 0,0 to settingsVSplitDivider-10, vsplitheight-42-peek("tabheight")-40, "HelpTree", 1, "Tree2"
	layout "left,bottom,right", "Tree2"
	textcontrol 0,vsplitheight-42-peek("tabheight")-30 to settingsVSplitDivider-14,vsplitheight-42-peek("tabheight")-10, "HelpFind", "Command", "", "Tree2"
	layout "standard", "Tree2"

	view dropzone "VSplit1"
	view dropzone "V2Split2"

	// a stackview with textedits in the upper right splitview
	// implement a dynamic stackview in future!
	// stackview 0,0 to settingsWidth-settingsVSplitDivider-11,settingsHSplitDivider-1, "Stack", MAXFILES+2, "HSplit1"
	stackview 0,0 to settingsWidth-settingsVSplitDivider-11-4,settingsHSplitDivider-1, "Stack", MAXFILES+2, "V2Split2"
	stackview 0,0 to settingsV2SplitDivider,settingsHSplitDivider-1, "Lines", MAXFILES+2, "V2Split1"
	for i=1 to MAXFILES
		// textedit 37,0 to settingsWidth-settingsVSplitDivider-12,settingsHSplitDivider-1, "Text"+str$(i), 3, "Stack"+str$(i)
		textedit 1,1 to settingsWidth-settingsVSplitDivider-12-5,settingsHSplitDivider-2, "Text"+str$(i), 3, "Stack"+str$(i)
		textedit set "Text"+str$(i), "wordwrap", false
		textedit set "Text"+str$(i), "textwidth", 4000
		textedit set "Text"+str$(i), "tabwidth", settingsTabSpaces*7
		textedit set "Text"+str$(i), "font", settingsFontFamily$+","+settingsFontStyle$+","+str$(settingsFontSize)
		textedit set "Text"+str$(i), "autoindent", settingsAutoIndent

		// layout "left,top,bottom", "Lines"+str$(i)
		// view 0,0 to 36,settingsHSplitDivider-1, "Lines"+str$(i), "LineStack"+str$(i)
		draw set settingsFontFamily$+","+settingsFontStyle$+","+str$(settingsFontSize), "Lines"+str$(i)
		layout "standard", "Stack"+str$(i)

		textedit set "Text"+str$(i), "autocomplete-start", settingsACNumChar
		handle = open(ideDir$+"data/autocompletion")
		if(handle) then
			while(not eof(handle))
				line input #handle tmp$
				textedit set "Text"+str$(i), "autocomplete", tmp$
			wend
			close(handle)
		endif

		handle = open(ideDir$+"data/color1")
		if(handle) then
			while(not eof(handle))
				line input #handle tmp$
				textedit color "Text"+str$(i), "color1", tmp$
			wend
			close(handle)
		endif
		handle = open(ideDir$+"data/color2")
		if(handle) then
			while(not eof(handle))
				line input #handle tmp$
				textedit color "Text"+str$(i), "color2", tmp$
			wend
			close(handle)
		endif
		handle = open(ideDir$+"data/color3")
		if(handle) then
			while(not eof(handle))
				line input #handle tmp$
				textedit color "Text"+str$(i), "color3", tmp$
			wend
			close(handle)
		endif
		handle = open(ideDir$+"data/color4")
		if(handle) then
			while(not eof(handle))
				line input #handle tmp$
				textedit color "Text"+str$(i), "color4", tmp$
			wend
			close(handle)
		endif
		handle = open(ideDir$+"data/color5")
		if(handle) then
			while(not eof(handle))
				line input #handle tmp$
				textedit color "Text"+str$(i), "char-color", tmp$
			wend
			close(handle)
		endif
	next i

	textedit 1,1 to settingsWidth-settingsVSplitDivider-12-5,settingsHSplitDivider-2, "Text"+str$(MAXFILES+1), 1, "Stack"+str$(MAXFILES+1)
	textedit set "Text"+str$(MAXFILES+1), "font", settingsFontFamily$+","+settingsFontStyle$+","+str$(settingsFontSize)
	textedit set "Text"+str$(MAXFILES+1), "editable", false
	textedit color "Text"+str$(MAXFILES+1), "color1", "Name:"
	textedit color "Text"+str$(MAXFILES+1), "color1", "Synopsis:"
	textedit color "Text"+str$(MAXFILES+1), "color1", "Description:"
	textedit color "Text"+str$(MAXFILES+1), "color1", "Example:"
	textedit color "Text"+str$(MAXFILES+1), "color1", "Design:"
	textedit color "Text"+str$(MAXFILES+1), "color1", "Layout:"
	textedit color "Text"+str$(MAXFILES+1), "color1", "Message:"
	textedit color "Text"+str$(MAXFILES+1), "color1", "Related:"
	SyntaxLoadTree(ideDir$+"data/Help_En.dat", "HelpTree") 

	// UpdateLines(0, globalHSplitDivider-1-peek("scrollbarwidth"), 1, 15)
	UpdateLines(0, 1200, 1, globalRealFontSize)

	layout "h-center, v-center", "Stack"+str$(MAXFILES+2)
	// view (settingsWidth-settingsVSplitDivider-12)/2-150,(settingsHSplitDivider-1)/2-190 to (settingsWidth-settingsVSplitDivider-12)/2+150,(settingsHSplitDivider-1)/2+190, "Logo", "Stack"+str$(MAXFILES+2)
	view (settingsWidth-settingsVSplitDivider-12-41-4)/2-150,(settingsHSplitDivider-1)/2-190 to (settingsWidth-settingsVSplitDivider-12-41-4)/2+150,(settingsHSplitDivider-1)/2+190, "Logo", "Stack"+str$(MAXFILES+2)
	draw set "bgcolor", 255,255,255, "Stack"+str$(MAXFILES+2)
	draw set "bgcolor", 255,255,255, "Logo"
	err = draw image 0,0 to 300,-1, ideDir$+"img/logo.png", "Logo"
	stackview set "Stack", MAXFILES+2
	stackview set "Lines", MAXFILES+2
	layout "standard", "Stack"+str$(MAXFILES+2)

	hsplitheight = settingsHeight-settingsHSplitDivider-peek("scrollbarwidth")-peek("menuheight")-42

	// the tabview in the lower right splitview
	tabview 0,0 to settingsWidth-settingsVSplitDivider-11,hsplitheight, "HTab", "bottom", "HSplit2"
	tabview add "HTab", "yab Output"
	tabview add "HTab", "Immediate"
	tabview add "HTab", "Find and replace"
	if(not globalNoRCS) then
		tabview add "HTab", "Version Control"
	endif

	hsplitheight = hsplitheight-peek("tabheight")-12
	tabwidth = settingsWidth-settingsVSplitDivider-21

	// the output box
	listbox 0,0 to tabwidth,hsplitheight, "YabOutputList", 1, "HTab1"

	// the immediate stuff
	layout "left,right,top", "HTab2"
	textcontrol 5,5 to tabwidth-110,25, "ImmediateInput", "Command", "", "HTab2"
	layout "right,top", "HTab2"
	button tabwidth-100,3 to tabwidth-10,23, "ImmediateExecute", "Execute", "HTab2"
	layout "standard", "HTab2"
	textedit 10,35 to tabwidth-10,hsplitheight-10, "ImmediateOutput", 1, "HTab2"
	textedit set "ImmediateOutput", "editable", false

	// search and replace
	layout "left,top", "HTab3"
	w = draw get "Text-width", MyTranslate$("Find:"), "HTab3"
	draw text 55-w,23, "Find:", "HTab3"
	w = draw get "Text-width", MyTranslate$("Replace:"), "HTab3"
	draw text 55-w,48, "Replace:", "HTab3"
	textcontrol 55,10 to 290,30, "FindTCFind", "", "", "HTab3"
	textcontrol 55,35 to 290,55, "FindTCReplace", "", "", "HTab3"
	checkbox 55,60, "FindCS", "Case Sensitive", settingsFindCS, "HTab3"
	MyLine(300,5,300,90,"HTab3")
	button 310,10 to 460,30, "FindFind", "Find", "HTab3"
	button 310,35 to 460,55, "FindReplace", "Find and replace", "HTab3"
	button 310,60 to 460,80, "FindReplAll", "Replace All", "HTab3"

	// the statusbar
	layout "left, bottom", "MainView"
	view 0,settingsHeight-peek("scrollbarwidth") to 2000,settingsHeight, "Statusbar", "MainView"
	draw set "highcolor", 200,200,200, "Statusbar"
	draw line 0,0 to 2000,0, "Statusbar"
	draw set "highcolor", 184,184,184, "Statusbar"
	draw line 0,1 to 2000,1, "Statusbar"
	draw set "highcolor", 239,239,239, "Statusbar"
	draw line 0,2 to 2000,2, "Statusbar"
	
	if(window count>1) window close "Splash"

	window set "MainView", "moveto", settingsX, settingsY

	return
end sub


// (De-)activate menus
sub ActivateMenus(toActivate)
	local tmp$

	if(toActivate) then
		tmp$ = "Enable"
	else
		tmp$ = "Disable"
	endif

	menu set "File", "Close", tmp$, "MainView"
	menu set "File", "Save", tmp$, "MainView"
	menu set "File", "Save as...", tmp$, "MainView"
	menu set "File", "Save as template...", tmp$, "MainView"
	menu set "File", "Export as HTML...", tmp$, "MainView"
	menu set "File", "Page setup...", tmp$, "MainView"
	menu set "File", "Print...", tmp$, "MainView"
	
	menu set "Edit", "Undo", tmp$, "MainView"
	menu set "Edit", "Cut", tmp$, "MainView"
	menu set "Edit", "Copy", tmp$, "MainView"
	menu set "Edit", "Paste", tmp$, "MainView"
	menu set "Edit", "Select all", tmp$, "MainView"
	menu set "Edit", "Find", tmp$, "MainView"
	menu set "Edit", "Find again", tmp$, "MainView"
	menu set "Edit", "Find and replace", tmp$, "MainView"

	menu set "Program", "Run", tmp$, "MainView"
	menu set "Program", "Run in Terminal", tmp$, "MainView"
	menu set "Program", "Set run parameters...", tmp$, "MainView"
	menu set "Program", "Build Factory...", tmp$, "MainView"
	menu set "Program", "Open project folder...", tmp$, "MainView"

	if(not globalNoRCS) then
		menu set "RCS", "Check In", tmp$, "MainView"
		menu set "RCS", "Check Out", tmp$, "MainView"
		menu set "RCS", "Version History...", tmp$, "MainView"
	endif

	menu set "Tools", "Pattern editor...", tmp$, "MainView"
	menu set "Tools", "Color selection...", tmp$, "MainView"
	
	menu set "View", "Next file", tmp$, "MainView"
	menu set "View", "Previous file", tmp$, "MainView"	
	menu set "View", "Auto indent", tmp$, "MainView"
	menu set "View", "Auto completion", tmp$, "MainView"
	menu set "View", "Refresh colors", tmp$, "MainView"
	menu set "View", "Reformat sourcecode", tmp$, "MainView"
	menu set "View", "Undo reformat", "disable", "MainView"
	menu set "View", "Options...", tmp$, "MainView"

	option set "ToolbarSave", "Enabled", toActivate
	option set "ToolbarClose", "Enabled", toActivate
	option set "ToolbarCut", "Enabled", toActivate
	option set "ToolbarCopy", "Enabled", toActivate
	option set "ToolbarPaste", "Enabled", toActivate
	option set "ToolbarUndo", "Enabled", toActivate
	option set "ToolbarFind", "Enabled", toActivate
	option set "ToolbarText", "Enabled", toActivate
	option set "ToolbarRun", "Enabled", toActivate
	option set "ToolbarRunTerm", "Enabled", toActivate
	option set "ToolbarPattern", "Enabled", toActivate 
	option set "ToolbarBuild", "Enabled", toActivate
	option set "ToolbarOptions", "Enabled", toActivate
	option set "ToolbarGotoLine", "Enabled", toActivate 

	option set "FindTCFind", "Enabled", toActivate
	option set "FindTCReplace", "Enabled", toActivate
	option set "FindCS", "Enabled", toActivate
	option set "FindFind", "Enabled", toActivate
	option set "FindReplace", "Enabled", toActivate
	option set "FindReplAll", "Enabled", toActivate

	return
end sub

// (De-)activate menus when help is selected
sub ActivateHelpMenus(toActivate)
	local tmp$

	if(toActivate = 1) then
		tmp$ = "Enable"
	else
		tmp$ = "Disable"
	endif

	if(toActivate = -1) then
		menu set "File", "Open...", tmp$, "MainView"
		menu set "File", "New...", tmp$, "MainView"
	else
		menu set "File", "Open...", "Enable", "MainView"
		menu set "File", "New...", "Enable", "MainView"
	endif
	menu set "File", "Close", tmp$, "MainView"
	menu set "File", "Save", tmp$, "MainView"
	menu set "File", "Save as...", tmp$, "MainView"
	menu set "File", "Save as template...", tmp$, "MainView"
	menu set "File", "Export as HTML...", tmp$, "MainView"
	
	menu set "Edit", "Undo", tmp$, "MainView"
	menu set "Edit", "Cut", tmp$, "MainView"
	menu set "Edit", "Paste", tmp$, "MainView"
	menu set "Edit", "Find and replace", tmp$, "MainView"

	menu set "Program", "Run", tmp$, "MainView"
	menu set "Program", "Run in Terminal", tmp$, "MainView"
	menu set "Program", "Set run parameters...", tmp$, "MainView"
	menu set "Program", "Build Factory...", tmp$, "MainView"
	menu set "Program", "Open project folder...", tmp$, "MainView"

	if(not globalNoRCS) then
		menu set "RCS", "Check In", tmp$, "MainView"
		menu set "RCS", "Check Out", tmp$, "MainView"
		menu set "RCS", "Version History...", tmp$, "MainView"
	endif

	menu set "Tools", "Pattern editor...", tmp$, "MainView"
	menu set "Tools", "Color selection...", tmp$, "MainView"

	menu set "View", "Next file", tmp$, "MainView"
	menu set "View", "Previous file", tmp$, "MainView"	
	menu set "View", "Auto indent", tmp$, "MainView"
	menu set "View", "Auto completion", tmp$, "MainView"
	menu set "View", "Refresh colors", tmp$, "MainView"
	menu set "View", "Reformat sourcecode", tmp$, "MainView"
	menu set "View", "Undo reformat", "disable", "MainView"

	if(toActivate = -1) then
		option set "ToolbarOpen", "Enabled", false
		option set "ToolbarNew", "Enabled", false
		toActivate = 0 
	else
		option set "ToolbarOpen", "Enabled", true
		option set "ToolbarNew", "Enabled", true
	endif
	option set "ToolbarSave", "Enabled", toActivate
	option set "ToolbarClose", "Enabled", toActivate
	option set "ToolbarCut", "Enabled", toActivate
	option set "ToolbarPaste", "Enabled", toActivate
	option set "ToolbarUndo", "Enabled", toActivate
	option set "ToolbarText", "Enabled", toActivate
	option set "ToolbarRun", "Enabled", toActivate
	option set "ToolbarRunTerm", "Enabled", toActivate
	option set "ToolbarPattern", "Enabled", toActivate 
	option set "ToolbarBuild", "Enabled", toActivate
	option set "ToolbarGotoLine", "Enabled", toActivate 

	option set "FindTCReplace", "Enabled", toActivate
	option set "FindReplace", "Enabled", toActivate
	option set "FindReplAll", "Enabled", toActivate

	return
end sub

// Update the line numbering
sub UpdateLines(starty, height, topline, fontHeight)
	local i, pos
	local t$

	if(globalCurrentText > 0) then
		pos = splitview get "V2Split", "Divider" - 3
		draw flush "Lines"+str$(globalCurrentText)
		for i=fontHeight-4-starty to height step fontHeight
			t$ = str$(int(i/fontHeight)+topline+1)
			draw text pos-(draw get "text-width", t$, "Lines"+str$(globalCurrentText)),i, t$, "Lines"+str$(globalCurrentText)
		next i
	endif
	return
end sub

// Open new file
sub NewDocument(foundEmpty)
	local inloop
	local browse$
	local i, n, err, nTemplates, isButton
	local handle, handle2
	local x, y, winSize, w, t
	local t$, txt$

	x = (peek("desktopwidth")-500)/2
	y = (peek("desktopheight")-390)/2-50
	if(y<50) y=50

	window open x+200-3000,y+150-3000 to x+700-3000,y+440-3000, "NewWindow", "yab-IDE New Program"
	window set "NewWindow", "Feel", "Modal-App"
	window set "NewWindow", "Flags", "not-zoomable, not-h-resizable, not-v-resizable"

	Header("New yab Program", "NewWindow", 500)
	
	text 10,50, "NewText1", "Please select one of the available templates for your program:", "NewWindow"
	listbox 10,70 to 166,200, "NewList", 1, "NewWindow"

	handle = open(ideDir$+"Templates/TemplateList", "r")
	if(handle>0) then
		nTemplates = 0
		while(not eof(handle))
			nTemplates = nTemplates + 1
			dim tmp$(nTemplates)
			tmp$(nTemplates) = GetLine$(handle)+"\n"
			tmp$(nTemplates) = left$(tmp$(nTemplates), len(tmp$(nTemplates))-1)
			if(left$(tmp$(nTemplates),1) = "#") nTemplates = nTemplates - 1
		wend
		close handle
	else
		dim tmp$(1)
		tmp$(1) = "Empty"
		nTemplates = 1
	endif	
	for i  = 1 to nTemplates step 4
		listbox add "NewList", tmp$(i)
	next i
	view 190,70 to 490,200, "NewImage", "NewWindow"

	browse$ = globalProjectDir$+"untitled"+str$(GetNewNumber(globalProjectDir$))+".yab"

	textcontrol 10,220 to 400,240, "NewName", "Name:", browse$, "NewWindow"
	button 410,220 to 490,240, "NewBrowse", "Browse...", "NewWindow"

	checkbox image 10,270, "NewAdvanced", ideDir$+"img/arrowdown.png", ideDir$+"img/arrowright.png", "", "", false, "NewWindow"
	winSize = false
	text 20,270, "NewText2", "Advanced Options", "NewWindow"
	button 430,260 to 490,280, "NewOk", "Ok", "NewWindow"
	option set "NewOk", "enabled", false
	isButton = false

	draw set "highcolor", 185,185,185, "NewWindow"
	draw line 0,252 to 500,252, "NewWindow"
	draw line 0,292 to 500,292, "NewWindow"
	draw set "highcolor", 239,239,239, "NewWindow"
	draw line 0,253 to 500,253, "NewWindow"
	draw line 0,293 to 500,293, "NewWindow"

	// button 260,300 to 280,310, "NewHelp", "?", "NewWindow"
	button 350,295 to 490,325, "NewDel", "Remove Template", "NewWindow"
	option set "NewDel", "enabled", false

	if(not globalNoRCS) then
		checkbox 10, 300, "NewCheckbox", "Use RCS Version Control", settingsUseRCS, "NewWindow"
		// option set "NewCheckbox", "enabled", false
		// option set "NewHelp", "enabled", false
	endif

	textcontrol 10,330 to 490,350, "NewProject", "Project Directory", globalProjectDir$, "NewWindow"

	window set "NewWindow", "moveto", x,y 

	inloop = true
	dim msg$(1)
	while(inloop)
		n = split(message$, msg$(), "|")
		for i = 1 to n
			if(DEBUG and msg$(i)<>"") print msg$(i)
			if(left$(msg$(i),16) = "NewList:_Invoke:") then
				msg$(i) = "NewOk"
			endif
			switch(msg$(i))
				case "NewOk"
					if(j>0) then
						browse$ = textcontrol get$ "NewName"
						if(arraysize(tmp$(), 1) = 1) then
							txt$ = ""
						else
							handle = open(ideDir$+"Templates/"+tmp$(j), "r")
							if(handle) then
								while(not eof(handle))
									txt$ = txt$ + GetLine$(handle)+"\n"
								wend
								close(handle)
								// txt$ = left$(txt$, len(txt$)-1)
							else
								alert MyTranslate$("Could not open template: ")+tmp$(j)+"\n\n"+MyTranslate$("Opening an empty file instead."), "Ok", "warning"
								txt$ = ""
							endif
						endif
						globalCurrentText = foundEmpty
						textedit add "Text"+str$(globalCurrentText), txt$
						textedit set "Text"+str$(globalCurrentText), "changed", true
						textedit set "Text"+str$(globalCurrentText), "gotoline", 1
						stackview set "Stack", globalCurrentText
						stackview set "Lines", globalCurrentText
						globalAllNames$(globalCurrentText) = browse$
						t = columnbox count "FileBox"
						columnbox add "FileBox", 1, t+1,20, "__Mime__=application/x-vnd.yab-app"
						columnbox add "FileBox", 2, t+1,20, GetFileName$(browse$)
						columnbox select "FileBox", t+1

						globalTextFinder(globalCurrentText) = t+1

						option set "Text"+str$(globalCurrentText), "focus", true
						oldScroll = -1
						globalNewNumber = globalNewNumber + 1
						globalNumOpenFiles = globalNumOpenFiles + 1
						inloop = false
					endif
					break
				case "NewAdvanced:ON"
				case "NewAdvanced:OFF"
					winSize = not winSize
					if(winSize) then
						window set "NewWindow", "MinimumTo", 500,360
						window set "NewWindow", "MaximumTo", 500,360
						window set "NewWindow", "ResizeTo", 500,360
					else
						window set "NewWindow", "MinimumTo", 500,290
						window set "NewWindow", "MaximumTo", 500,290
						window set "NewWindow", "ResizeTo", 500,290
					endif
					break	
				case "NewBrowse"
					browse$ = filepanel "Save-File", "New", globalProjectDir$
					if(browse$<>"") textcontrol set "NewName", browse$
					break
				case "NewWindow:_QuitRequested"
					inloop = false
					break
				case "_QuitRequested"
					//emergency break
					exit(1)
					break
				case "NewDel"
					t$ = listbox get$ "NewList", (j-1)/4+1
					t = alert MyTranslate$("Really delete template")+" \""+t$+"\"?", "Yes", "Cancel", "", "warning"
					if(t = 1) then
						if((j-1)/4+1 < 4) then
							alert "This standard template can not be deleted!", "Ok", "warning"
						else	
							handle = open(ideDir$+"Templates/TemplateList", "r")
							handle2 = open("/tmp/TemplateList", "w")
							if(handle) then
								if(handle2) then
									while(not eof(handle))
										t$ = GetLine$(handle)+"\n"
										if(left$(t$,len(t$)-1)<>tmp$(j)) then
											print #handle2 t$;
										else
											t$ = GetLine$(handle)+"\n"
											t$ = GetLine$(handle)+"\n"
											t$ = GetLine$(handle)+"\n"
										endif
									wend
									close(handle2)
									system("mv /tmp/TemplateList "+ideDir$+"Templates/TemplateList")
									system("rm "+ideDir$+tmp$(j+1))
									system("rm "+ideDir$+"Templates/"+tmp$(j))
									listbox remove "NewList", (j-1)/4+1
									listbox select "NewList", (j-5)/4+1
									msg$(i) = "NewList:_Select:"+str$((j-5)/4+1)
									alert "Template successfully removed.", "Ok", "info"
								else
									alert "Error while deleting template!", "Ok", "stop"
								endif
								close(handle)
							else
								alert "Error while deleting template!", "Ok", "stop"
							endif
						endif
					endif

					break
			end switch
			if(left$(msg$(i),16) = "NewList:_Select:") then
				draw rect 0,0 to 200,140, "NewImage"
				draw flush "NewImage"
				j = (val(mid$(msg$(i),17,len(msg$(i))-1))-1)*4+1
				if(arraysize(tmp$(),1)>=j+1) then
					err = draw image 50,0 to 250,100, ideDir$+tmp$(j+1), "NewImage"
				endif
				if(arraysize(tmp$(),1)>=j+2) then
					draw text 10,110, tmp$(j+2), "NewImage"
				endif
				if(arraysize(tmp$(),1)>=j+3) then
					draw text 10,125, tmp$(j+3), "NewImage"
				endif
				if(not isButton) then
					isButton = false
					option set "NewOk", "enabled", true
					option set "NewDel", "enabled", true
				endif
			endif
		next i
	wend

	window close "NewWindow"
end sub

sub GetNewNumber(dir$)
	local tmp$
	local num: local i: local ret
	local numFound
	local t$(1)

	numFound = false
	ret = 0
	tmp$ = system$("ls "+dir$+"untitled*.yab")
	num = token(tmp$, t$(), "\n")
	while(not numFound)
		numFound = true
		for i=1 to num
			tmp$ = left$(t$(i), len(t$(i))-4)
			tmp$ = right$(tmp$, len(tmp$)-8-len(dir$))
			if(ret = val(tmp$)) then
				ret = ret + 1
				numFound = false
				break
			endif
		next i
		if(numFound) then
			for i=1 to MAXFILES
				tmp$ = dir$+"untitled"+str$(ret)+".yab"
				if(globalAllNames$(i) = tmp$) then
					ret = ret + 1
					numFound = false
					break
				endif
			next i
		endif
	wend
	return ret
end sub

sub ImmediateExec(command$)
	local result$
	
	if(instr(command$, "input")) then
		alert "Suspecting user input, therefore starting in a terminal.", "Ok", "info"
		result$ = system$("Terminal "+yabDir$+" -enter -execute '"+command$+":exit'")
	else
		result$ = system$(yabDir$+" -execute '"+command$+":exit' 2>&1")
		result$ = left$(result$, len(result$)-1)

		textedit clear "ImmediateOutput"
		textedit add "ImmediateOutput", result$
	endif

	return
end sub

sub GetFileName$(directory$)
	local lastSlash
	local j

	lastSlash = 0
	for j=1 to len(directory$)
		if(mid$(directory$,j,1)="/" and mid$(directory$,j-1,1)<>"/")
			lastSlash = j
	next j

	return right$(directory$,len(directory$)-lastSlash)
end sub

sub GetDirectory$(directory$)
	local lastSlash
	local j

	lastSlash = 0
	for j=1 to len(directory$)
		if(mid$(directory$,j,1)="/" and mid$(directory$,j-1,1)<>"/")
			lastSlash = j
	next j

	return left$(directory$,lastSlash)
end sub

sub ActivateText(num)
	globalCurrentText = num
	globalWasChanged = textedit get "Text"+str$(globalCurrentText), "hasChanged"
	stackview set "Stack", globalCurrentText
	stackview set "Lines", globalCurrentText
	option set "Text"+str$(globalCurrentText), "focus", true
	columnbox select "FileBox", globalTextFinder(num)
	oldScroll = -1  
	return
end sub

sub ReadLineFromAttr(filename$)
	a$=attribute get$ "",filename$
	if instr (a$,"linenumber") then  
	return attribute get "linenumber", filename$
	else return 0
	endif
end sub

sub UpdateStatusbar()
	static oldText$
	local newText$

	if(globalCurrentText = 0) then
		if(oldText$<>"") then
			oldText$ = ""
			draw flush "Statusbar"
			draw set "highcolor", 200,200,200, "Statusbar"
			draw line 0,0 to 2000,0, "Statusbar"
			draw set "highcolor", 184,184,184, "Statusbar"
			draw line 0,1 to 2000,1, "Statusbar"
			draw set "highcolor", 239,239,239, "Statusbar"
			draw line 0,2 to 2000,2, "Statusbar"
		endif
		return
	endif

	newText$ = globalAllNames$(globalCurrentText)
	if(textedit get "Text"+str$(globalCurrentText), "hasChanged") then
		newText$ = newText$ + MyTranslate$(" (not saved)   ")
	else
		newText$ = newText$ + "               "
	endif

	newText$ = newText$ + MyTranslate$("Line:")+" "+str$(textedit get "Text"+str$(globalCurrentText), "currentline")
	newText$ = newText$ + " / "+str$(textedit get "Text"+str$(globalCurrentText), "countlines")


	if(oldText$<>newText$) then
		draw flush "Statusbar"
	draw set "highcolor", 200,200,200, "Statusbar"
	draw line 0,0 to 2000,0, "Statusbar"
	draw set "highcolor", 184,184,184, "Statusbar"
	draw line 0,1 to 2000,1, "Statusbar"
	draw set "highcolor", 239,239,239, "Statusbar"
	draw line 0,2 to 2000,2, "Statusbar"
	draw set "highcolor", 0,0,0, "Statusbar"
		draw text 5,13, "File: ", "Statusbar"
		// draw set "highcolor", 0,200,0, "Statusbar"
		draw text (5+draw get "Text-Width", MyTranslate$("File: "), "Statusbar"),13, newText$, "Statusbar"
		// draw text (5+draw get "Text-Width", "Status: ", "Statusbar"),11, globalAllNames$(globalCurrentText)+" saved", "Statusbar"
		oldText$ = newText$
	endif

	return
end sub

sub WaitWindow(text$)
	local x
	local y
	local width
	local err

	x = peek("desktopwidth")/2 - 125
	y = peek("desktopheight")/2 - 100
	window open x,y to x+249,y+79, "WaitWindow", ""
	window set "WaitWindow", "feel", "modal-app" 
	window set "WaitWindow", "look", "modal" 
	window set "WaitWindow", "Flags", "not-closable, not-zoomable, not-h-resizable, not-v-resizable"
	err = draw image 0,0, ideDir$+"img/Loading.png", "WaitWindow"

	w = draw get "text-width", GetFileName$(text$), "WaitWindow"
	text 143-w/2,32, "TWait", GetFileName$(text$), "WaitWindow"

	w = draw get "text-width", MyTranslate$("Please wait..."), "WaitWindow"
	text 143-w/2,60, "TRunning2", "Please wait...", "WaitWindow"

	draw set "Bitstream Vera Sans, Bold Oblique, 14", "WaitWindow"
	w = draw get "text-width", MyTranslate$("Loading Program"), "WaitWindow"
	draw text 143-w/2,20, "Loading Program", "WaitWindow"
	 
	return
end sub

// Run the program and display its output
sub RunProgram(yabFile$)
	local tmp$, unique$
	local num, i, t, teamID, pos
	local x, y, err, w

	if(isRunning) return
	isRunning = true
	
	// easy way to make the tmp file sort-of unique
	unique$ = date$+time$

	x = peek("desktopwidth")/2 - 125
	y = peek("desktopheight")/2 - 100
	window open x,y to x+249,y+79, "Running", ""
	window set "Running", "feel", "modal-app" 
	window set "Running", "look", "modal" 
	window set "Running", "Flags", "not-closable, not-zoomable, not-h-resizable, not-v-resizable"
	err = draw image 0,0, ideDir$+"img/Running.png", "Running"

	w = draw get "text-width", GetFileName$(yabFile$), "Running"
	text 143-w/2,32, "TRunning", GetFileName$(yabFile$), "Running"
	button 150,50 to 240,75, "BRunning", "Break", "Running"

	draw set "Bitstream Vera Sans, Bold Oblique, 14", "Running"
	w = draw get "text-width", MyTranslate$("Running Program"), "Running"
	draw text 143-w/2,20, "Running Program", "Running"
	 
	// text 5,5, "TRunning", MyTranslate$("Now Running: ")+GetFileName$(yabFile$), "Running"
	// button 50,25 to 150,45, "BRunning", "Break", "Running"
	listbox clear "YabOutputList"
	window set "Running", "deactivate"

	if DEBUG print "cd "+GetDirectory$(yabFile$)+";"+yabDir$+" "+settingsYabParam$+" "+yabFile$+" "+settingsProgParam$+" &>/tmp/yab-log."+unique$+"  &"
	system("cd "+GetDirectory$(yabFile$)+";"+yabDir$+" "+settingsYabParam$+" "+yabFile$+" "+settingsProgParam$+" &>/tmp/yab-log."+unique$+" &")
	sleep 0.1
	while(teamID <> -1)
		teamID = thread get "teamid", yabDir$+" "+param$+yabFile$

		handle = open("/tmp/yab-log."+unique$,"r")
		if(handle) then
			seek handle,pos
			while(not eof(handle))
				tmp$ = GetLine$(handle)+"\n"
				listbox add "YabOutputList", left$(tmp$, len(tmp$)-1)
				listbox select "YabOutputList", listbox count "YabOutputList"
				pos = tell(handle)
			wend
			close(handle)
		endif

		if(instr(message$, "BRunning")) then
			t = thread remove "teamid", teamID
			if(not t) alert "Error! Program could not be killed.", "Oops", "stop"
			break
		endif
		sleep 0.1
	wend

	window close "Running"

	system("rm -f "+"/tmp/yab-log."+unique$+" >/dev/null")

	isRunning = false
	return
end sub

// Run the program in a terminal
sub RunInTerminal(yabFile$)
	local tmp$, param$
	local num, i, t, pos
	local x, y, err, w

	if(isRunning) return
	isRunning = true

	x = peek("desktopwidth")/2 - 150
	y = peek("desktopheight")/2 - 100
	window open x,y to x+299,y+79, "Running", ""
	window set "Running", "feel", "modal-app" 
	window set "Running", "look", "modal" 
	window set "Running", "Flags", "not-closable, not-zoomable, not-h-resizable, not-v-resizable"
	err = draw image 0,0, ideDir$+"img/Running.png", "Running"

	w = draw get "text-width", GetFileName$(yabFile$), "Running"
	text 168-w/2,32, "TRunning", GetFileName$(yabFile$), "Running"

	w = draw get "text-width", MyTranslate$("Close terminal to break program"), "Running"
	text 168-w/2,60, "TRunning2", "Close terminal to break program", "Running"

	draw set "Bitstream Vera Sans, Bold Oblique, 14", "Running"
	w = draw get "text-width", MyTranslate$("Running Program"), "Running"
	draw text 168-w/2,20, "Running Program", "Running"
	 
	window set "Running", "deactivate"
	sleep 0.1

	param$ = settingsYabParam$ + " -enter"
	tmp$ = system$("Terminal "+yabDir$+" "+param$+" "+yabFile$+" "+settingsProgParam$+" 2>&1")
	window close "Running"

	listbox clear "YabOutputList"
	dim result$(1)
	num = split(tmp$, result$(), "\n")
	for i = 1 to num
		listbox add "YabOutputList", result$(i)
	next i

	isRunning = false
	return
end sub

sub AboutWindow()
	local x
	local y
	local width
	local t
	local a$
	
	

	x = peek("desktopwidth")/2 - 200
	y = peek("desktopheight")/2 - 200
	window open x-3000,y-3000 to x+400-3000, y+300-3000, "AboutWindow", ""
	window set "AboutWindow", "look", "bordered"
	window set "AboutWindow", "feel", "modal-app"
	window set "AboutWindow", "MaximumTo", 400,300
	window set "AboutWindow", "MinimumTo", 400,300
	window set "AboutWindow", "Flags", "not-closable, not-zoomable, not-h-resizable, not-v-resizable"

	draw set "bgcolor", 255,255,255, "AboutWindow"
	draw set "lowcolor", 255,255,255, "AboutWindow"
	a$=system$("yab -v >& "+globalConfigDir$+"yabver" )
	t=open(globalConfigDir$+"yabver")
	line input #i a$
	close #t
	t=instr(a$,chr$(44))
	a$=left$(a$,t-1)
	a$="Running "+a$
	//a$=str$(peek(version))
	width=draw get "text-width", a$, "AboutWindow"
	draw text 200-width/2, 200,a$,"AboutWindow"

	width = draw get "text-width", "(c) 2006-2017 in terms of the Artistic License", "AboutWindow"
	draw text 198-width/2, 260, "(c) 2006-2017 in terms of the Artistic License", "AboutWindow"
	width= draw get "text-width", "Ported to Haiku PM by bbjimmy","AboutWindow"
	draw text 200-width/2, 240, "Ported to Haiku PM by bbjimmy","AboutWindow"
	width = draw get "text-width", "Coded by Jan, graphics by Genki, thanks to BeSly", "AboutWindow"
	draw text 200-width/2, 220, "Coded by Jan, graphics by Genki, thanks to BeSly", "AboutWindow"

	if(peek$("os") = "Haiku") then
		draw set "DejaVu Sans, Bold, 18", "AboutWindow"
	else
		draw set "Swis721 BT, Bold, 18", "AboutWindow"
	endif
	width = draw get "text-width", "yab-IDE", "AboutWindow"
	draw text 200-width/2, 25, "yab-IDE", "AboutWindow"
	//if(peek$("os") = "Haiku") then
		draw set "DejaVu Sans, Bold, 10", "AboutWindow"
	//else
	//	draw set "Swis721 BT, Bold, 10", "AboutWindow"
	//endif
	width = draw get "text-width", "Version "+versionnumber$, "AboutWindow"
	draw text 200-width/2, 40, "Version "+versionnumber$, "AboutWindow"

	t = draw image 120,40 to 280,-1, ideDir$+"img/yablogo.png", "AboutWindow"

	button 100,265 to 300,290, "AboutButton", "Close", "AboutWindow"
	option set "AboutButton", "focus", true

	window set "AboutWindow", "moveto", x,y

	while(not instr(message$, "AboutButton"))
	wend


	window close "AboutWindow"
	return
end sub

sub SaveAsTemplate()
	local x: local y
	local w: local i: local n
	local isButton
	local handle: local handle2
	local inloop
	local msg$(1)
	local name$: local description1$: local description2$: local image$
	local t$

	x = (peek("desktopwidth")-600)/2
	y = (peek("desktopheight")-200)/2-50
	if(y<50) y=50

	window open x-3000,y-3000 to x+600-3000,y+200-3000, "SaveTempWindow", "yab-IDE Save as Template"
	window set "SaveTempWindow", "Feel", "Modal-App"
	window set "SaveTempWindow", "Flags", "not-zoomable, not-h-resizable, not-v-resizable"

	Header("Save as Template", "SaveTempWindow", 600)

	text 10,50, "SaveTempText1", "Save your code as a template for other programs:", "SaveTempWindow"
	textcontrol 10,70 to 380,90, "SaveTempName", "Template Name", "", "SaveTempWindow"
	text 10,98, "SaveTempText2", "Description (not more than 30 characters per line)", "SaveTempWindow"
	textcontrol 5,110 to 380,120, "SaveTempDes1", "", "", "SaveTempWindow"
	textcontrol 5,130 to 380,150, "SaveTempDes2", "", "", "SaveTempWindow"

	draw set "highcolor", 0,0,0, "SaveTempWindow"
	draw set "lowcolor", 255,255,0, "SaveTempWindow"
	draw set 0, "240225195135015030060120"
	draw rect 390,50 to 590,150, "SaveTempWindow"
	draw set 0, "lowsolidfill"
	draw set "lowcolor", 216,216,216, "SaveTempWindow"
	draw rect 400,60 to 580,140, "SaveTempWindow"
	draw set 0, "highsolidfill"

	w = draw get "Text-width", MyTranslate$("Drop image here"), "SaveTempWindow"
	draw text 490-w/2,105, "Drop image here", "SaveTempWindow"
	view dropzone "SaveTempWindow"

	draw set "highcolor", 185,185,185, "SaveTempWindow"
	draw line 0,162 to 600,162, "SaveTempWindow"
	draw set "highcolor", 239,239,239, "SaveTempWindow"
	draw line 0,163 to 600,163, "SaveTempWindow"

	button 530,170 to 590,190, "SaveTempOk", "Save", "SaveTempWindow"
	option set "SaveTempOk", "enabled", false
	isButton = false

	option set "SaveTempName", "focus", true

	window set "SaveTempWindow", "moveto", x,y

	inloop = true 
	while(inloop)
		n = split(message$, msg$(), ":|")
		for i = 1 to n
			if(DEBUG and msg$(i)<>"") print msg$(i)
			// check for emergency exit
			if(i > 1) then
				if(msg$(i) = "_QuitRequested" and msg$(i-1) <> "SaveTempWindow") then
					exit(1)
				endif
			else
				if(msg$(i) = "_QuitRequested") then
					exit(1)
				endif
			endif
			switch(msg$(i))
				case "_Dropped"
					if(arraysize(msg$(),1)>=i+1) then
						w = draw image 390,50 to 590,150, msg$(i+1), "SaveTempWindow"
						if(w<>0) then
							alert "Could not load image!", "Ok", "warning"
						else
							image$ = msg$(i+1)
						endif
					endif
					break
				case "SaveTempOk"
					name$ = left$(textcontrol get$ "SaveTempName", 50)
					description1$ = left$(textcontrol get$ "SaveTempDes1", 30)
					description2$ = left$(textcontrol get$ "SaveTempDes2", 30)
					imageShort$ = GetFileName$(image$)
					system("cp "+image$+" "+ideDir$+"Templates/img/"+imageShort$)
					handle = open(ideDir$+"Templates/TemplateList", "a")
					if(handle) then
						print #handle "#"
						print #handle name$
						print #handle "Templates/img/"+imageShort$
						print #handle description1$
						print #handle description2$
						close(handle)
						handle2 = open(ideDir$+"Templates/"+name$, "w")
						if(handle2) then
							t$ = textedit get$ "Text"+str$(globalCurrentText)
							print #handle t$;
							close(handle2)
						else
							alert "Error while saving template!", "Ok", "warning"
						endif
					else
						alert "Error while saving template!", "Ok", "warning"
					endif
					inloop = false
					break
				case "_QuitRequested"
					inloop = false
					break
			end switch
		next i

		name$ = textcontrol get$ "SaveTempName"
		if(name$<>"" and not isButton) then
			option set "SaveTempOk", "enabled", true
			isButton = true
		endif
		if(name$="" and isButton) then
			option set "SaveTempOk", "enabled", false
			isButton = false
		endif
	wend

	window close "SaveTempWindow"
	return
end sub

sub SaveCurrentFile()
local savetext$
	handle = open(globalAllNames$(globalCurrentText), "w")
        if(handle) then
		savetext$=textedit get$ "Text"+str$(globalCurrentText)
		if right$(savetext$,1)<>chr$(10) savetext$=savetext$+chr$(10)
        	print #handle savetext$;
        	close(handle)
		tmpCurrentLine = textedit get "Text"+str$(globalCurrentText), "currentline"
		print "ATTR SET ";
		print str$(tmpCurrentLine)
		attribute set "Int", "linenumber", str$(tmpCurrentLine), globalAllNames$(globalCurrentText)
		textedit set "Text"+str$(globalCurrentText), "changed", false
		globalWasChanged = false
		columnbox add "FileBox", 1, globalTextFinder(globalCurrentText), 20, "__Mime__=application/x-vnd.yab-app"
	else
		alert "File could not be saved!", "Ok", "warning"
		return false
	endif
	return true
end sub

sub Header(headerText$, window$, size)
	local w
	local head$

	head$ = window$+"Header"
	layout "none", window$
	view 0,0 to size,40, head$, window$
	draw set "bgcolor", 230,230,255, head$
	draw set "lowcolor", 230,230,255, head$
	if(peek$("os") = "Haiku") then
		draw set "DejaVu Sans, Condensed Bold, 18", head$
	else
		draw set "Swis721 BT, Bold, 18", head$
	endif
	draw set "highcolor", 0,0,0, head$
	w = draw get "Text-width", MyTranslate$(headerText$), head$
	draw text size-w-10,25, headerText$, head$
	draw set "highcolor", 239,239,239, head$
	draw line 0,40 to size,40, head$
	draw set "highcolor", 185,185,185, head$
	draw line 0,39 to size,39, head$
	return
end sub

// open the build factory window
sub Building()
	local x, y, inloop, isEmpty
	local binName$, t$, myTab$, result$
	local msg$(1)
	local i, n, tmp
	
	
	x = (peek("desktopwidth")-500)/2
	y = (peek("desktopheight")-400)/2-50
	if(y<50) y=50

	window open x-3000,y-3000 to x+500-3000,y+400-3000, "BuildWindow", "yab-IDE Build Factory"
	window set "BuildWindow", "Feel", "Modal-App"
	window set "BuildWindow", "Flags", "not-zoomable, not-h-resizable, not-v-resizable"
	
	Header("Build Factory", "BuildWindow", 500)

	if(right$(globalAllNames$(globalCurrentText),4) = ".yab") then
		binName$ = left$(globalAllNames$(globalCurrentText), len(globalAllNames$(globalCurrentText))-4)
	else
		binName$= globalAllNames$(globalCurrentText)+".bin"
	endif
	
	while (instr(binName$, "/"))
		pos=instr(binName$, "/")
		binName$=right$(binName$,len(binName$)-pos)
		wend
	
	
	isEmpty = false

	textcontrol 10,50 to 380,70, "BuildPath", "Target file name:", binName$, "BuildWindow"
	AppSig$ = getappsig$(globalAllNames$(globalCurrentText))
	
	if AppSig$="" AppSig$="application/x-vnd."+binName$
	textcontrol 10,80 to 380,100, "AppSig", "Application Signature:", AppSig$, "BuildWindow"
	//button 390,50 to 490,70, "BuildBrowse", "Browse", "BuildWindow"

	button 390,100 to 490,130, "BuildBuild", "Create Binary", "BuildWindow" 

	MyLine(0,140,500,140, "BuildWindow")
	textedit 10,155 to 490,390, "BuildOutput", 3, "BuildWindow"
	textedit set "BuildOutput", "editable", false
	textedit set "BuildOutput", "wordwrap", false
	textedit set "BuildOutput", "textwidth", 4000

	window set "BuildWindow", "moveto", x, y

	if(left$(system$("gcc 2>&1"),4) <> "gcc:") then
		alert "The compiler GCC was not found!\n\nPlease install a complete Haiku system.", "Ok", "stop"
		window close "BuildWindow"
		return
	endif

	textedit add "BuildOutput", MyTranslate$("Build Factory Output\n\n")

	inloop = true
	while(inloop)
		n = split(message$, msg$(), "|")
		for i = 1 to n
			if(DEBUG and msg$(i)<>"") print msg$(i)
			switch(msg$(i))
				case "BuildBuild"
					option set "BuildBuild", "enabled", false
					option set "BuildPath", "enabled", false
					//option set "BuildBrowse", "enabled", false
					option set "AppSig", "enabled", false
					AppSig$=textcontrol get$ "AppSig"
					if AppSig$="" AppSig$="application/x-vnd.yab-app"
					binName$=textcontrol get$ "BuildPath"
					textedit add "BuildOutput", MyTranslate$("Please wait, processing... (this may take a long time!)\n\n")
					print "cd "+buildDir$+"; "+yabDir$+" BuildFactory.yab "+binName$+" "+globalAllNames$(globalCurrentText)+" "+AppSig$+" 2>&1\n\n"
					result$ = system$("cd "+buildDir$+";  yab BuildFactory.yab "+binName$+" "+globalAllNames$(globalCurrentText)+" "+AppSig$+" yab-ide  2>&1")
					textedit add "BuildOutput", result$
					

					option set "BuildBuild", "enabled", true
					option set "BuildPath", "enabled", true 
					//option set "BuildBrowse", "enabled", true 
					option set "AppSig", "enabled", true
					
					if(IfExists(buildDir$+"/"+binName$)) then
						alert "Build was successful", "Ok", "info"
					else
						alert "Build failed!", "Ok", "warning"
					endif
					system("rm "+ buildDir$+"/"+binName$)
					break
				//case "BuildBrowse"
				//	t$ = filepanel "save-file", "Save", GetDirectory$(binName$)
				//	if(t$<>"") then
				//		textcontrol set "BuildPath", t$
				//		binName$ = t$
				//	endif
				//	break
				case "_QuitRequested"
				case "BuildWindow:_QuitRequested"
					inloop = false
					break
			end switch
		next i
		if(not isEmpty and textcontrol get$ "BuildPath" = "") then
			AppSig$=textcontrol get$ "AppSig"
			option set "BuildBuild", "enabled", false
			isEmpty = true
		endif
		if(isEmpty and textcontrol get$ "BuildPath" <> "") then
			AppSig$=textcontrol get$ "AppSig"
			option set "BuildBuild", "enabled", true
			isEmpty = false
		endif
		
		
		
	wend
	window close "BuildWindow"
	return
end sub

// open the option window
sub OptionWindow()
	local x, y, inloop
	local msg$(1), style$(1)
	local styleNum, styleCount
	local i, n, optCurrent
	local tmp$
	local handle, j, hasItem
	local family$, style$, size$
	local defaultFamily

	x = (peek("desktopwidth")-650)/2
	y = (peek("desktopheight")-400)/2-50
	if(y<50) y=50

	window open x+100-3000,y+150-3000 to x+750-3000,y+550-3000, "OptWindow", "yab-IDE Options"
	window set "OptWindow", "Feel", "Modal-App"
	window set "OptWindow", "Flags", "not-zoomable, not-h-resizable, not-v-resizable"

	Header("Options", "OptWindow", 650)

	draw set "highcolor", 185,185,185, "OptWindow"
	draw line 11,51 to 138,51, "OptWindow"
	draw line 10,50 to 139,50, "OptWindow"
	draw line 11,51 to 11,388, "OptWindow"
	draw line 10,50 to 10,389, "OptWindow"
	draw set "highcolor", 239,239,239, "OptWindow"
	draw line 12,389 to 139,389, "OptWindow"
	draw line 11,390 to 139,390, "OptWindow"
	draw line 139,52 to 139,389, "OptWindow"
	draw line 140,51 to 140,390, "OptWindow"
	draw set "highcolor", 0,0,0, "OptWindow"

	treebox 12,52 to 138,388, "OptTree", 0, "OptWindow"
	// treebox add "OptTree", "Interpreter"
	// treebox add "OptTree", "Interpreter", "Libraries", true
	// treebox add "OptTree", "Interpreter", "Execution", true
	treebox add "OptTree", "Editor"
	treebox add "OptTree", "Editor", "Auto completion", true
	// treebox add "OptTree", "Editor", "Syntax Highlighting", true
	treebox add "OptTree", "Editor", "General", true
	treebox add "OptTree", "Environment"
	if(not settingsRCSOff) treebox add "OptTree", "Environment", "Version Control", true
	treebox add "OptTree", "Environment", "Language", true
	treebox add "OptTree", "Environment", "Directories", true
	treebox select "OptTree", 2

	// button 430,370 to 530,390, "OptDefault", "Default", "OptWindow"
	// button 540,370 to 640,390, "OptOk", "Close", "OptWindow"

	// MyLine(0,362,650,362,"OptWindow")

	optCurrent = 1
	stackview 150,50 to 640,390, "OptStack", 4, "OptWindow"

	// General
	boxview 0,0 to 490, 340, "OptBox3", "General", 2, "OptStack1"
	spincontrol 10,5, "OptGenSpin", "Number of spaces per tab:", 1,20,1, "OptBox3"
	spincontrol set "OptGenSpin", settingsTabSpaces
	MyLine(10,35,470,35, "OptBox3")
	checkbox 10,45, "OptGenSaving", "Ask about saving before running a program", settingsAskForSaving, "OptBox3"
	checkbox 10,65, "OptGenReformat", "Show warning when reformating sourcecode did not close all loops and conditions", settingsReformatAlert, "OptBox3"
	checkbox 10,85, "OptGenReformatUndo", "Show warning before undo reformating", settingsReformatUndoAlert, "OptBox3"
	checkbox 10,105, "OptGenReplaceAll", "Show warning before applying Replace All", settingsFindAlert, "OptBox3"
	MyLine(10,135,470,135, "OptBox3")

	text 10,145, "OptGenTxt", "Select font for editor:", "OptBox3"
	dropbox 12,165 to 240,185, "OptGenFontFamily", "Font Family", "OptBox3"
	dropbox 250,165 to 370,185, "OptGenFontStyle", "Font Style", "OptBox3"
	spincontrol 380,160, "OptGenFontSize", "Font Size", 8,50,1, "OptBox3"

	n = token(draw get$ "FontFamily", msg$(), "|")
	for i = 1 to n
		dropbox add "OptGenFontFamily", msg$(i)
		if(msg$(i) = settingsFontFamily$) j = i
		if(msg$(i) = "Courier10 BT") defaultFamily = i
	next i
	if(j>0) then
		dropbox select "OptGenFontFamily", j
		n = token(draw get$ settingsFontFamily$, msg$(), "|")
		for i = 1 to n
			dropbox add "OptGenFontStyle", msg$(i)
			if(msg$(i) = settingsFontStyle$) j = i
		next i
		if(j>0) dropbox select "OptGenFontStyle", j
	endif
	spincontrol set "OptGenFontSize", settingsFontSize

	view 20,205 to 460,255, "OptGenSample", "OptBox3"
	draw set "bgcolor", 255,255,255, "OptGenSample"
	draw set settingsFontFamily$+","+settingsFontStyle$+","+str$(settingsFontSize), "OptGenSample"
	n = draw get "text-width", MyTranslate$("My hovercraft is full of eels."), "OptGenSample"
	draw text (440-n)/2,(50-settingsFontSize)/2+settingsFontSize, "My hovercraft is full of eels.", "OptGenSample"
	MyLine(10,290,470,290,"OptBox3")
	button 320,297 to 470,317, "OptDefault", "Factory Settings", "OptBox3"

	// Syntax Highlighing
	// boxview 0,0 to 490, 340, "OptBox4", "Syntax Highlighting", 2, "OptStack2"

	// Auto completion
	boxview 0,0 to 490, 340, "OptBox5", "Auto completion", 2, "OptStack2"
	checkbox 10,10, "OptACCheck", "Enable auto completion", settingsAutoCompletion, "OptBox5"
	spincontrol 10,30, "OptACNum", "Number of characters for starting completion:", 1,20,1, "OptBox5"
	spincontrol set "OptACNum", settingsACNumChar
	MyLine(10,60,470,60,"OptBox5")
	listbox 10,75 to 180,275, "OptACList", 1, "OptBox5"
	textcontrol 190,185 to 470,205, "OptACTC", "New Entry:", "", "OptBox5"
	button 320,215 to 470,235, "OptACAdd", "Add New Entry", "OptBox5"
	MyLine(190,245,470,245,"OptBox5")
	MyLine(190,175,470,175,"OptBox5")
	button 370,255 to 470,275, "OptACRemove", "Remove Entry", "OptBox5"
	text 190,75, "OptACText1", "Note: You have to restart the IDE to update the", "OptBox5"
	text 190,90, "OptACText2", "autocompletion when removing entries.", "OptBox5"
	handle = open(ideDir$+"data/autocompletion", "r")
	if(handle) then
		while(not eof(handle))
			tmp$ = GetLine$(handle)+"\n"
			listbox add "OptACList", left$(tmp$, len(tmp$)-1)
		wend
		close(handle)
	endif
	MyLine(10,290,470,290,"OptBox5")
	button 320,297 to 470,317, "OptDefault", "Factory Settings", "OptBox5"

	// Dirs
	boxview 0,0 to 490, 340, "OptBox6", "Directories", 2, "OptStack3"
	text 10,10, "OptDirTxt", "Note: Only change the directories, when you know what you are doing!", "OptBox6"
	MyLine(10,30,470,30, "OptBox6")
	textcontrol 10,45 to 470,65, "OptDirBinDir", "Default yab Binary", yabDir$, "OptBox6"
	// MyLine(10,45,470,45, "OptBox6")
	// textcontrol 10,60 to 360,80, "OptDirProjDir", "Project Directory", globalProjectDir$, "OptBox6"
	textcontrol 10,80 to 470,100, "OptDirYabDir", "Default yab Directory", settingsYabDir$, "OptBox6"
	MyLine(10,115,470,115, "OptBox6")
	MyLine(10,290,470,290,"OptBox6")
	button 320,297 to 470,317, "OptDefault", "Factory Settings", "OptBox6"

	// Language
	boxview 0,0 to 490, 340, "OptBox8", "Language", 2, "OptStack4"
	checkbox 10,10, "OptLangCheck", "Use automatic localization", restartSettingsLangUse, "OptBox8"
	MyLine(10,40,470,40,"OptBox8")
	columnbox 10,55 to 470,275, "OptLangList", false, "", "OptBox8"
	columnbox column "OptLangList", "Supported Languages", 1, 460,460,460, "align-left"
	MyLine(10,290,470,290,"OptBox8")
	button 320,297 to 470,317, "OptDefault", "Factory Settings", "OptBox8"
	columnbox color "OptLangList", "Selection-Active", 220,220,250 
	columnbox color "OptLangList", "Row-Divider", 255,255,255 
	tmp$ = system$("ls /boot/common/data/locale/catalogs/"+settingsLangPath$+"/*.catalog")
	n = token(tmp$, msg$(), "\n")
	for i = 1 to n
		columnbox add "OptLangList", 1,i,18,msg$(i)
	next i

	window set "OptWindow", "moveto", x,y

	inloop = true
	while(inloop)
		n = split(message$, msg$(), "|")
		for i = 1 to n
			if(DEBUG and msg$(i)<>"") print msg$(i)
			switch(msg$(i))
				case "_QuitRequested"
					// emergency quit
					exit(1)
					break
				case "OptOk"
				case "OptWindow:_QuitRequested"
					inloop = false
					break

				// General
				case "OptGenSaving:ON"
				case "OptGenSaving:OFF"
					settingsAskForSaving = not settingsAskForSaving
					break
				case "OptGenReformat:ON"
				case "OptGenReformat:OFF"
					settingsReformatAlert = not settingsReformatAlert
					break
				case "OptGenReformatUndo:ON"
				case "OptGenReformatUndo:OFF"
					settingsReformatUndoAlert = not settingsReformatUndoAlert
					break
				case "OptGenReplaceAll:ON"
				case "OptGenReplaceAll:OFF"
					settingsFindAlert = not settingsFindAlert
					break

				// Autocompletion
				case "OptACCheck"
					settingsAutoCompletion = not settingsAutoCompletion
					break
				case "OptACRemove"
					break
				case "OptACAdd"
					tmp$ = textcontrol get$ "OptACTC"
					if(tmp$<>"") then
						hasItem = false
						for j=1 to listbox count "OptACList"
							if(tmp$ = listbox get$ "OptACList", i) then
								hasItem = true
								break
							endif
						next j
						if(not hasItem) then
							listbox add "OptACList", tmp$
							listbox sort "OptACList"
						else
							alert "Entry already exists.", "Ok", "info"
						endif
					endif
					break
					
				// Language
				case "OptLangCheck:ON"
				case "OptLangCheck:OFF"
					restartSettingsLangUse = not restartSettingsLangUse
					alert "Restart yab-IDE to change localization", "Ok", "info"
					break

				// Default
				case "OptDefault"
					t = stackview get "OptStack"
					switch(t)
						case 1
							settingsAskForSaving = true
							settingsReformatAlert = true
							settingsReformatUndoAlert = true
							settingsFindAlert = true
							settingsTabSpaces = 4
							settingsFontStyle$ = "Roman"
							settingsFontSize = 12
							spincontrol set "OptGenSpin", settingsTabSpaces
							checkbox set "OptGenSaving", settingsAskForSaving
							checkbox set "OptGenReformat", settingsReformatAlert
							checkbox set "OptGenReformatUndo", settingsReformatUndoAlert
							checkbox set "OptGenReplaceAll", settingsFindAlert
							dropbox select "OptGenFontFamily", defaultFamily
							if(settingsFontFamily$<> "Courier10 BT") then
								settingsFontFamily$ = "Courier10 BT"
								dropbox clear "OptGenFontStyle"
								styleCount = token(draw get$ settingsFontFamily$, style$(), "|")
								for styleNum = 1 to styleCount
									dropbox add "OptGenFontStyle", style$(styleNum)
								next styleNum
								dropbox select "OptGenFontStyle", 1
								OptionUpdateSample()
							endif
							spincontrol set "OptGenFontSize", settingsFontSize
							for j = 1 to MAXFILES
								textedit set "Text"+str$(j), "TabWidth", settingsTabSpaces*7
							next j
							break
						case 2
							settingsAutoCompletion = true
							settingsACNumChar = 2
							checkbox set "OptACCheck", settingsAutoCompletion
							spincontrol set "OptACNum", settingsACNumChar
							break
						case 3
							if(system("test -d /boot/apps/Development/yab-1.0/") = 0) then
								settingsYabDir$ = "/boot/apps/Development/yab-1.0/"
							elsif(system("test -d /boot/apps/yab-1.0/") = 0) then
								settingsYabDir$ = "/boot/apps/yab-1.0/"
							else
								alert "Could not find yab 1.0 directory!\n\nPlease do a proper installation.", "Ok", "warning"
							endif
							textcontrol set "OptDirYabDir", settingsYabDir$

							if(system("test -e /boot/home/config/bin/yab") = 0) then
								yabDir$ = "/boot/home/config/bin/yab"
							else
								alert "Could not find yab binary!\n\nPlease do a proper installation.", "Ok", "warning"
							endif
							textcontrol set "OptDirBinDir", yabDir$
							break
						case 4
							if(restartSettingsLangUse = false) then
								restartSettingsLangUse = true
								checkbox set "OptLangCheck",restartSettingsLangUse
								alert "Restart yab-IDE to change localization", "Ok", "info"
							endif
							break
					end switch
					break
			end switch

			// Font stuff
			if(left$(msg$(i), 17) = "OptGenFontFamily:") then
				settingsFontFamily$ = right$(msg$(i), len(msg$(i))-17)
				dropbox clear "OptGenFontStyle"
				styleCount = token(draw get$ settingsFontFamily$, style$(), "|")
				for styleNum = 1 to styleCount
					dropbox add "OptGenFontStyle", style$(styleNum)
				next styleNum
				dropbox select "OptGenFontStyle", 1
				settingsFontStyle$ = style$(1)
				OptionUpdateSample()
			endif
			if(left$(msg$(i), 16) = "OptGenFontStyle:") then
				settingsFontStyle$ = right$(msg$(i), len(msg$(i))-16)
				OptionUpdateSample()
			endif

			if(left$(msg$(i), 8) = "OptACTC:") then
				option set "OptACAdd", "focus", true
			endif
			if(left$(msg$(i), 16) = "OptTree:_Select:") then
				t = val(right$(msg$(i), len(msg$(i))-16))
				tmp$ = treebox get$ "OptTree", t
				switch(tmp$)
					case MyTranslate$("General"): t = 1: break
					// case MyTranslate$("Syntax Highlighting"): t = 2: break
					case MyTranslate$("Auto completion"): t = 2: break
					case MyTranslate$("Directories"): t = 3: break
					case MyTranslate$("Language"): t = 4: break
					// case MyTranslate$("Version Control"): t = 6: break
					default: t = 0: break
				end switch
				if(t>0) then 
					stackview set "OptStack", t
					optCurrent = t
				endif
			endif
			
			if(left$(msg$(i), 13) = "OptDirYabDir:") then
				tmp$ = right$(msg$(i), len(msg$(i))-13)
				if(system("test -d "+tmp$) = 0) then
					settingsYabDir$ = tmp$
					alert MyTranslate$("New yab directory set to:\n\n")+tmp$+MyTranslate$("\n\nRestart the IDE using the new directory."), "Ok", "info"
				else
					alert MyTranslate$("Invalid directory:\n\n")+tmp$, "Ok", "warning"
					textcontrol set "OptDirYabDir", settingsYabDir$
				endif
			endif
			if(left$(msg$(i), 13) = "OptDirBinDir:") then
				tmp$ = right$(msg$(i), len(msg$(i))-13)
				if(system("test -e "+tmp$) = 0) then
					yabDir$ = tmp$
					alert MyTranslate$("yab binary set to:\n\n")+tmp$, "Ok", "info"
				else
					alert MyTranslate$("Invalid file:\n\n")+tmp$, "Ok", "warning"
					textcontrol set "OptDirBinDir", yabDir$
				endif
			endif
		next i
		if(spincontrol get "OptGenFontSize" <> settingsFontSize) then
			settingsFontSize = spincontrol get "OptGenFontSize"
			OptionUpdateSample()
		endif
		if(spincontrol get "OptGenSpin" <> settingsTabSpaces) then
			settingsTabSpaces = spincontrol get "OptGenSpin"
			for j = 1 to MAXFILES
				textedit set "Text"+str$(j), "TabWidth", settingsTabSpaces*7
			next j
		endif
	wend

	window close "OptWindow"
	
	return
end sub

// draw the example text (OptionWindow)
sub OptionUpdateSample()
	local n
	local scroll, scrollLine, scrollPos

	draw flush "OptGenSample"
	draw set settingsFontFamily$+","+settingsFontStyle$+","+str$(settingsFontSize), "OptGenSample"
	n = draw get "text-width", MyTranslate$("My hovercraft is full of eels."), "OptGenSample"
	draw text (440-n)/2,50-(50-settingsFontSize)/2, "My hovercraft is full of eels.", "OptGenSample"
	for n = 1 to MAXFILES
		textedit set "Text"+str$(n), "font", settingsFontFamily$+","+settingsFontStyle$+","+str$(settingsFontSize)
		draw set settingsFontFamily$+","+settingsFontStyle$+","+str$(settingsFontSize), "Lines"+str$(n)
	next n
	if(globalCurrentText>0) then
		globalRealFontSize = textedit get "Text"+str$(globalCurrentText), "line-height", 1
		scroll = textedit get "Text"+str$(globalCurrentText), "vertical-scrollbar"
		scrollLine = int(scroll/globalRealFontSize)
		scrollPos = mod(scroll,globalRealFontSize)
		UpdateLines(scrollPos, 1200, scrollLine, globalRealFontSize)
	endif
	return
end sub

// draw a sort of 3D line
sub MyLine(x1,y1,x2,y2,View$)
	draw set "highcolor", 185,185,185, View$
	draw line x1,y1 to x2,y2, View$
	draw set "highcolor", 239,239,239, View$
	if(x1=x2) then
		draw line x1+1,y1 to x2+1,y2, View$
	else
		draw line x1,y1+1 to x2,y2+1, View$
	endif
	draw set "highcolor", 0,0,0, View$
	return
end sub

// only translates when a translation is wanted
sub MyTranslate$(txt$)
	if(settingsLangUse) return menu translate$(txt$)
	return txt$
end sub

// returns true if filename$ exists
sub IfExists(filename$)
	return not system("test -e "+filename$)
end sub

// Create a new toolbar.
// 
// x1,y1 is the upper left starting point
// x2 is the right border of the toolbar
// note: the toolbar is always 30 pixels in height!
// id$ is the toolbar ID
// dir$ is the directory, where the icons can be found
// view$ is the view on which the Toolbar is created
// 
// Note: this will change the layout of your view view$.
sub ToolbarCreate(x1,y1,x2, id$, dir$, view$)
	layout "left, right", view$
	view x1,y1 to x2,y1+32, id$, view$
	// layout "left,right", id$
	draw set "bgcolor", 222,219,222, id$
	// view 0,30 to x2,32, id$+"line", id$
	// draw set "bgcolor", 185,185,185, id$+"line"
	layout "none", id$
	position = 10
	directory$ = dir$
	toolbarview$ = id$
	return
end sub

// Add an icon to the toolbar.
sub ToolbarAddIcon(id$, tooltip$, pressed$, normal$, disabled$)
	button image position,7, id$, directory$+pressed$, directory$+normal$, directory$+disabled$, toolbarview$
	tooltip id$, tooltip$
	position = position + 25
	return
end sub

// Add a separator to the toolbar.
sub ToolbarAddSeparator()
	draw set "highcolor", 185,185,185, toolbarview$
	draw line position-2,5 to position-2,25,toolbarview$ 
	draw set "highcolor", 239,239,239, toolbarview$
	draw line position-1,5 to position-1,25, toolbarview$
	position = position + 5
	return
end sub

// Open the pattern calculation window
sub OpenCalcPattern(x,y)
	local i, j, w
	local msg$(1)
	local inloop, n

	window open x,y to x+259,y+400, "CalcPattern", "yab-IDE Pattern editor"
	window set "CalcPattern", "Feel", "Modal-App"
	window set "CalcPattern", "Flags", "not-zoomable, not-h-resizable, not-v-resizable"

	Header("Pattern editor", "CalcPattern", 260)

        draw set "highcolor", 239,239,239, "CalcPattern"
        draw line 0,300 to 259,300, "CalcPattern"
        draw set "highcolor", 185,185,185, "CalcPattern"
        draw line 0,299 to 259,299, "CalcPattern" 

	view 10,50 to 249,289, "VDraw", "CalcPattern"
	draw set "bgcolor", 255, 255, 255, "VDraw"
	draw set "lowcolor", 0, 0, 0, "VDraw"
	
	view 10,310 to 90,390, "VPattern", "CalcPattern"
	draw set "bgcolor", 255, 255, 255, "VPattern"
	draw set "lowcolor", 0, 0, 0, "VPattern"
	draw set "highcolor", 255, 255, 255, "VPattern"
	
	button 100,370 to 249,390, "CalcPatternInsert", "Insert Pattern", "CalcPattern"

	UpdatePattern(pattern())
	draw set 0, "LowSolidFill"
	draw set "lowcolor", 0, 0, 0, "VDraw"
	for i = 0 to 7
		for j = 0 to 7
			if(pattern(i,j) = 1) then
				draw rect i*30,j*30 to i*30+29,j*30+29, "VDraw"
			endif
		next j
	next i
	draw set 0, "HighSolidFill"

	inloop = true
	while(inloop)
		CalcPatternMouse(pattern())
		n = token(message$, msg$(), "|")
		for i = 1 to n
			switch(msg$(i))
				case "CalcPatternInsert"
					textedit add "Text"+str$(globalCurrentText), CalcPatternInsert$(pattern())
					break
				case "CalcPattern:_QuitRequested"
					settingsCalcPatternX = window get "CalcPattern", "Position-X"
					settingsCalcPatternY = window get "CalcPattern", "Position-Y"
					window close "CalcPattern"
					inloop = false
					break
				case "_QuitRequested"
					//emergency break
					exit(1)
					break
			end switch
		next i
	wend
	return
end sub

// mouse stuff (PatternEditor)
sub CalcPatternMouse(pattern())
	local help$
	local i, j, refresh
	
	mousex = 0
	mousey = 0
	mouselmb = 0
	mousemmb = 0
	mousermb = 0
	
	
	refresh = 0
	
	if(ismousein("VDraw")) then
		GetMouseData("VDraw",239,239)
	endif
	
	if(mouselmb) then
		x = int(mousex/30)
		y = int(mousey/30)
		if(pattern(x,y) = 0) then
			pattern(x,y) = 1
			draw set "lowcolor", 0, 0, 0, "VDraw"
			draw set 0, "LowSolidFill"
			draw rect x*30,y*30 to x*30+29,y*30+29, "VDraw"
			UpdatePattern(pattern())
			refresh = refresh + 1
		endif
	endif
	
	if(mousermb) then
		x = int(mousex/30)
		y = int(mousey/30)
		if(pattern(x,y) = 1) then
			pattern(x,y) = 0
			draw set "lowcolor", 255, 255, 255, "VDraw"
			draw set 0, "LowSolidFill"
			draw rect x*30,y*30 to x*30+29,y*30+29, "VDraw"
			draw set "lowcolor", 0, 0, 0, "VDraw"
			UpdatePattern(pattern())
			refresh = refresh + 1
		endif
	endif

	if(refresh = 15) then
		draw flush "VDraw"
		draw flush "VPattern"
		draw set "lowcolor", 0, 0, 0, "VDraw"
		for i = 0 to 7
			for j = 0 to 7
				if(pattern(i,j)) then
				draw set 0, "LowSolidFill"
				draw rect i*30,j*30 to i*30+29,j*30+29, "VDraw"
				draw set 0, "HighSolidFill"
				endif
			next j
		next i
		UpdatePattern(pattern())
		refresh = 0
	endif

	return
end sub

// get pattern string (PatternEditor)
sub CalcPatternInsert$(pattern())
	local i, j
	local t$, p$

	p$ = "\""
	for i = 0 to 7
		t$ = ""
		for j = 0 to 7
			t$ = t$ + str$(1-pattern(j,i))
		next j
		t = dec(t$,2)
		if(t<100) p$ = p$ + "0"
		if(t<10) p$ = p$ + "0"
		p$ = p$ + str$(t)
	next i
	p$ = p$ + "\""
	return p$
end sub

// get mouse stuff (PatternEditor)
sub GetMouseData(view$,maxx, maxy)
	local n
	local mouse$(1)

	mousemsg$ = mouse message$(view$)
	n = split(mousemsg$, mouse$(), ":")
	mousex = val(mouse$(1))
	mousey = val(mouse$(2))
	mouselmb = val(mouse$(3))
	mousemmb = val(mouse$(4))
	mousermb = val(mouse$(5))
	if(mousex<0) mousex = 0
	if(mousey<0) mousey = 0
	if(mousex>maxx) mousex = maxx
	if(mousey>maxy) mousey = maxy

	return
end sub

// update pattern (PatternEditor)
sub UpdatePattern(pattern())
	local i, j
	local t$, p$

	for i = 0 to 7
		t$ = ""
		for j = 0 to 7
			t$ = t$ + str$(1-pattern(j,i))
		next j
		t = dec(t$,2)
		if(t<100) p$ = p$ + "0"
		if(t<10) p$ = p$ + "0"
		p$ = p$ + str$(t)
	next i
	draw flush "VPattern"
	draw set 0, p$
	draw rect 0,0 to 80,80, "VPattern"
	draw set 0, "HighSolidFill"
	return
end sub

// Open the color selection window
sub OpenColorSelection(x,y,r,g,b)
	local i, j, w, n, num
	local tmp$, msg$(1), col$(1)
	local inloop

	window open x,y to x+366,y+270, "ColorSelect", "yab-IDE Color selection"
	window set "ColorSelect", "Feel", "Modal-App"
	window set "ColorSelect", "Flags", "not-zoomable, not-h-resizable, not-v-resizable"
	
	Header("Color selection", "ColorSelect", 366)

        draw set "highcolor", 239,239,239, "ColorSelect"
        draw line 0,233 to 366,233, "ColorSelect" 
	draw line 71,55 to 71,116, "ColorSelect"
	draw line 10,116 to 71,116, "ColorSelect"
        draw set "highcolor", 185,185,185, "ColorSelect"
        draw line 0,232 to 366,232, "ColorSelect"
	draw line 9,54 to 9,115, "ColorSelect"
	draw line 9,54 to 70,54, "ColorSelect"

	view 10,55 to 70,115, "ColorSelectRect", "ColorSelect"
	draw set "highcolor", r,g,b, "ColorSelectRect"
	draw rect 0,0 to 60,60, "ColorSelectRect"
	colorcontrol 80,59, "ColorControl", "ColorSelect"
	colorcontrol set "ColorControl", r,g,b

	draw set "highcolor", 0,0,0, "ColorSelect"
	draw text 10,140, "Default Colors:", "ColorSelect"
	draw set 1, "HighSolidFill"
	for i = 45 to 305 step 30
		for j=155 to 186 step 30
			draw set 1, "HighSolidFill"
			draw rect i,j to i+30,j+30, "ColorSelect"
			draw set 0, "HighSolidFill"
			tmp$ = str$((j-125)/30)+str$((i-15)/30)
			view i+1,j+1 to i+29,j+29, "Color"+tmp$, "ColorSelect"
			switch tmp$
				case "11"
					draw set "bgcolor", 0,0,0, "Color11"
					tooltip "Color11", "Black"
					break
				case "12"
					draw set "bgcolor", 96,96,96, "Color12"
					tooltip "Color12", "Darken 4"
					break
				case "13"
					draw set "bgcolor", 128,128,128, "Color13"
					tooltip "Color13", "Darken 3"
					break
				case "14"
					draw set "bgcolor", 152,152,152, "Color14"
					tooltip "Color14", "Darken 2"
					break
				case "15"
					draw set "bgcolor", 184,184,184, "Color15"
					tooltip "Color15", "Darken 1"
					break
				case "16"
					draw set "bgcolor", 216,216,216, "Color16"
					tooltip "Color16", "Default Background"
					break
				case "17"
					draw set "bgcolor", 232,232,232, "Color17"
					tooltip "Color17", "Lighten 1"
					break
				case "18"
					draw set "bgcolor", 240,240,240, "Color18"
					tooltip "Color18", "Lighten 2"
					break
				case "19"
					draw set "bgcolor", 255,255,255, "Color19"
					tooltip "Color19", "White"
					break
				case "21"
					draw set "bgcolor", 255,0,0, "Color21"
					tooltip "Color21", "Red"
					break
				case "22"
					draw set "bgcolor", 192,128,0, "Color22"
					tooltip "Color22", "Brown"
					break
				case "23"
					draw set "bgcolor", 255,255,0, "Color23"
					tooltip "Color23", "Yellow"
					break
				case "24"
					draw set "bgcolor", 0,255,0, "Color24"
					tooltip "Color24", "Green"
					break
				case "25"
					draw set "bgcolor", 0,255,255, "Color25"
					tooltip "Color25", "Cyan"
					break
				case "26"
					draw set "bgcolor", 128,192,255, "Color26"
					tooltip "Color26", "Light Blue"
					break
				case "27"
					draw set "bgcolor", 0,0,255, "Color27"
					tooltip "Color27", "Blue"
					break
				case "28"
					draw set "bgcolor", 255,0,255, "Color28"
					tooltip "Color28", "Magenta"
					break
				case "29"
					draw set "bgcolor", 192,128,255, "Color29"
					tooltip "Color29", "Light Magenta"
					break
			end switch
		next j
	next i

	draw set 0, "HighSolidFill"
	
	button 256,240 to 356,260, "ColorSelectInsert", "Insert Color", "ColorSelect"

	inloop = true
	while(inloop)
		ColorSelectMouse()
		n = token(message$, msg$(), "|")
		for i = 1 to n
			if(left$(msg$(i),13) =  "ColorControl:") then
				tmp$ = right$(msg$(i), len(msg$(i))-13)
				dim col$(3)
				num = token(tmp$, col$(), ":")
				if(num = 3) then
					draw flush "ColorSelectRect"
					draw set "highcolor", val(col$(1)), val(col$(2)), val(col$(3)), "ColorSelectRect"
					draw rect 0,0 to 60,60, "ColorSelectRect" 
				endif
			endif
			switch(msg$(i))
				case "ColorSelectInsert"
					textedit add "Text"+str$(globalCurrentText), ColorSelectInsert$()
					break
				case "ColorSelect:_QuitRequested"
					settingsColorSelectX = window get "ColorSelect", "Position-X"
					settingsColorSelectY = window get "ColorSelect", "Position-Y"
					settingsColorSelectR = colorcontrol get "ColorControl", "red"
					settingsColorSelectG = colorcontrol get "ColorControl", "green"
					settingsColorSelectB = colorcontrol get "ColorControl", "blue"
					window close "ColorSelect"
					inloop = false
					break
				case "_QuitRequested"
					//emergency break
					exit(1)
					break
			end switch
		next i
	wend
	return
end sub

// get the color string (ColorSelect)
sub ColorSelectInsert$()
	local r, g, b

	r = colorcontrol get "ColorControl", "red"
	g = colorcontrol get "ColorControl", "green"
	b = colorcontrol get "ColorControl", "blue"

	return " "+str$(r)+", "+str$(g)+", "+str$(b)
end sub

// check mouse in ColorSelect
sub ColorSelectMouse()
	local i, j
	local tmp$

	for i = 1 to 9
		for j = 1 to 2
			tmp$ = "Color"+str$(j)+str$(i)
			if(ismousein(tmp$) and IsButtonPressed(tmp$)) then
				switch tmp$
					case "Color11"
						SetColor(0,0,0)
						break
					case "Color12"
						SetColor(96,96,96)
						break
					case "Color13"
						SetColor(128,128,128)
						break
					case "Color14"
						SetColor(152,152,152)
						break
					case "Color15"
						SetColor(184,184,184)
						break
					case "Color16"
						SetColor(216,216,216)
						break
					case "Color17"
						SetColor(232,232,232)
						break
					case "Color18"
						SetColor(240,240,240)
						break
					case "Color19"
						SetColor(255,255,255)
						break
					case "Color21"
						SetColor(255,0,0)
						break
					case "Color22"
						SetColor(192,128,0)
						break
					case "Color23"
						SetColor(255,255,0)
						break
					case "Color24"
						SetColor(0,255,0)
						break
					case "Color25"
						SetColor(0,255,255)
						break
					case "Color26"
						SetColor(128,192,255)
						break
					case "Color27"
						SetColor(0,0,255)
						break
					case "Color28"
						SetColor(255,0,255)
						break
					case "Color29"
						SetColor(192,128,255)
						break
				end switch
			endif
		next j
	next i
end sub

// check for pressed mouse button (ColorSelect)
sub IsButtonPressed(view$)
        local n, t
	local mouselmb

	t = false
	dim mouse$(1)
	repeat
        	mousemsg$ = mouse message$(view$)
        	n = split(mousemsg$, mouse$(), ":")
        	mouselmb = val(mouse$(3))
		if(mouselmb) t = true
		if(not ismousein(view$)) then
			t = false
			mouselmb = 0
		endif
	until (mouselmb = 0)
        return t
end sub  

// set a color to RGB (ColorSelect)
sub SetColor(r,g,b)
	colorcontrol set "ColorControl", r,g,b
	draw flush "ColorSelectRect"
	draw set "highcolor", r,g,b, "ColorSelectRect"
	draw rect 0,0 to 60,60, "ColorSelectRect"
	return
end sub

// beautify the code by reformating it
sub ReformatSource$(code$)
	local tablevel, num, i, j, k
	local tmp$, returnSource$
	local hasThen, isInTicks, firstcase

	dim beginCommand$(12)
	dim endCommand$(15)

	beginCommand$(1) = "if"
	beginCommand$(2) = "switch"
	beginCommand$(3) = "for"
	beginCommand$(4) = "while"
	beginCommand$(5) = "do"
	beginCommand$(6) = "repeat"
	beginCommand$(7) = "case"
	beginCommand$(8) = "default"
	beginCommand$(9) = "else"
	beginCommand$(10) = "elsif"
	beginCommand$(11) = "sub"
	beginCommand$(12) = "export"

	endCommand$(1) = "end if"
	endCommand$(2) = "end-if"
	endCommand$(3) = "endif"
	endCommand$(4) = "fi"
	endCommand$(5) = "end switch"
	endCommand$(6) = "end-switch"
	endCommand$(7) = "next"
	endCommand$(8) = "wend"
	endCommand$(9) = "loop"
	endCommand$(10) = "until"
	endCommand$(11) = "else"
	endCommand$(12) = "elsif"
	endCommand$(13) = "end sub"
	endCommand$(14) = "case"
	endCommand$(15) = "default"
	
	dim reformat$(1)
	tablevel = 0
	firstcase = 0
	num = split(code$, reformat$(), "\n")

	for i=1 to num
		tmp$ = ltrim$(lower$(reformat$(i)))
		for j=1 to 15
			if(left$(tmp$, len(endCommand$(j))) = endCommand$(j) and (len(tmp$) = len(endCommand$(j)) or instr(" \n\t\f\v\r(:/", mid$(tmp$,len(endCommand$(j))+1,1)))) then
				if(not firstcase) then
					if(j = 5 or j = 6) tablevel = tablevel - 1
					tablevel = tablevel - 1
					// if(tablevel<0) tablevel = 0
				endif
				firstcase = 0
				break
			endif
		next j

		for j=1 to tablevel
			returnSource$ = returnSource$ + "\t"
		next j

		for j=1 to 12
			if(left$(tmp$, len(beginCommand$(j))) = beginCommand$(j) and (len(tmp$) = len(beginCommand$(j)) or instr(" \n\t\f\v\r(:/", mid$(tmp$,len(beginCommand$(j))+1,1)))) then
				hasThen = true 
				if(beginCommand$(j) = "switch") then
					firstcase = 1
				elsif(beginCommand$(j) = "if") then
					isInTicks = false
					hasThen = false
					for k=1 to len(tmp$)-3
						if(mid$(tmp$,k,1)="\"" and mid$(tmp$,k-1,1)<>"\\") isInTicks = not isInTicks
						if(not isInTicks and mid$(tmp$,k,4) = "then") then
							hasThen = true
							break
						endif
					next k
				endif
				if(hasThen) tablevel = tablevel + 1
				break
			endif
		next j
		returnSource$ = returnSource$ + ltrim$(reformat$(i))
		if(i<num) returnSource$ = returnSource$ + "\n"
	next i

	ReformatError(true, tablevel)

	return returnSource$
end sub

sub ReformatError(isSetting, ifSettingsThenError)
	static tabbingError
	
	if(isSetting) then
		tabbingError = ifSettingsThenError
	else
		return tabbingError
	endif
end sub

// Return true when the program named programName$ is running 
// otherwise return false
sub IsProgramRunning(programName$)
	local tmp$

	tmp$ = system$("ps |grep '"+programName$+"'")

	if(instr(tmp$, programName$) and not left$(tmp$,10) = "/bin/grep ") return true
	return false
end sub

// Returns the team id of the program programName$;
// returns 0 when the program was not found
sub GetTeamID(programName$)
	local tmp$
	local ret
	local t

	ret = 0
	tmp$ = system$("ps "+programName$+"|grep '"+programName$+"'")
	t = instr(tmp$, programName$)

	if(t>0 and left$(tmp$,10) <> "/bin/grep ") then
		ret = val(mid$(tmp$, t+7+len(programName$), len(tmp$)-t-7-len(programName$)))
	endif

	return ret
end sub

// Send the kill signal to all members of the team of programName$
// Returns true when successful and false otherwise
sub KillTeam(programName$)
	local ps$(1)
	local found
	local i, n

	n = token(system$("ps "+programName$), ps$(), chr$(10))
	found = false

	while(i<=n)
		if(instr(ps$(i), programName$)) then
			found = true
			i = i + 1
			while(val(ps$(i))>0 and i<=n)
				system("kill "+str$(val(ps$(i))))
				i = i + 1
			wend
		endif
		i = i + 1
	wend
	
	return found
end sub

// Load the syntax tree into the given tree box from the TreeFile$ file.
sub SyntaxLoadTree(TreeFile$, TreeBoxID$)
	local info, level, handle, inloop
	local tmp$


	// Clear the treebox first
	treebox clear TreeBoxID$

	// count the number of info texts
	info = 0
	// three levels: toplevel, sublevel and info text level
	level = 0
	// read data from file return the file handle 
	handle = open (TreeFile$, "r")
	if(not handle) return 0

	// read the file
	inloop = true
 	while(not eof(handle) and inloop)
  		tmp$ = GetLine$(handle)
  		// if it is not a comment...
  		if(not (left$(tmp$,1) = "&")) then
   			switch level
    				case 0  // toplevel
     					treebox add TreeBoxID$, tmp$
     					break
    				case 1  // sublevel
     					n = instr(tmp$, ":")
     					treebox add TreeBoxID$, left$(tmp$,n-1), right$(tmp$, len(tmp$)-n), 0
     					break
   			end switch
  		else
   			if(instr(tmp$, "toplevel")) level = 0
   			if(instr(tmp$, "sublevel")) level = 1
   			if(instr(tmp$, "infotext")) inloop = false
  		endif
 	wend
	close handle
	return 1
end sub

// Read the info text for Command$ from TreeFile$ with the index file IndexFile$.
sub SyntaxGetInfoText$(TreeFile$, IndexFile$, Command$)
	local handle, position, inloop 
	local infotext$

	// first read the seek position
	inloop = true
	handle = open (IndexFile$, "r")
	if(not handle) return ""

	while(not eof(handle) and inloop)
			tmp$ = GetLine$(handle)
			if(tmp$=Command$) then
				if (not eof(handle)) then
					tmp$ = GetLine$(handle)
					position = val(tmp$)
				endif
				inloop = false
			endif
		wend
	close handle

	// a seek position is found; return the info text.
	handle = open (TreeFile$, "r")
	if(not handle) return ""
		seek handle, position, "begin"
		tmp$ = GetLine$(handle)
		inloop = true
		while(not eof(handle) and inloop)
			tmp$ = GetLine$(handle)
			if(left$(tmp$,1) = "&") then
				inloop = false
			else
				infotext$ = infotext$ + tmp$ + chr$(10)
			endif
		wend
	close handle

	return infotext$
end sub

// Read a line from a file
sub GetLine$(handle)
	local tmp$, retString$

	while(tmp$<>chr$(10) and tmp$<>chr$(13) and not eof(handle))
		tmp$ = chr$(peek(handle))
		if(tmp$<>chr$(10) and tmp$<>chr$(13)) retString$ = retString$ + tmp$
	wend

	return retString$
end sub

// Open ASCII table window
sub AsciiWindow()
	local n, x, y

	window open 200,100 to 600,515, "AsciiView", "yab-IDE ASCII table"
	window set "AsciiView", "flags", "Not-Zoomable, not-h-resizable, not-v-resizable"

	Header("ASCII table", "AsciiView", 400)

	draw set "highcolor", 239,239,239, "AsciiView"
	draw line 6,405 to 395,405, "AsciiView"
	draw line 395,51 to 395,405, "AsciiView"
	draw set "highcolor", 185,185,185, "AsciiView"
	draw line 5,50 to 394,50, "AsciiView"
	draw line 5,50 to 5,404, "AsciiView"
	draw set "highcolor", 255,255,255, "AsciiView"
	draw rect 6,51 to 394,404, "AsciiView"
	draw set "highcolor", 0,0,0, "AsciiView"

	x = 10
	y = 65
	for n = 32 TO 126
		draw text x,y, str$(n)+chr$(32)+chr$(n), "AsciiView" 
		x = x+50
		if x >= 365 then
			x = 10
			y = y+30
		end if
	next n 	

	while(not instr(message$, "Quit"))
	wend
	window close "AsciiView"
	return
end sub

// set the run parameters
sub SetRunParameters()
	local tmp$
	local inloop

	window open 200,100 to 500,215, "RunParam", "yab-IDE Set run parameters"
	window set "RunParam", "flags", "Not-Zoomable, not-h-resizable, not-v-resizable"

	Header("Set run parameters", "RunParam", 300)

	textcontrol 10,50 to 290,70, "RunParamYab", "yab Parameters:", settingsYabParam$, "RunParam"
	textcontrol 10,80 to 290,110, "RunParamProg", "Program Parameters:", settingsProgParam$, "RunParam"

	inloop = true
	while(inloop)
		if(instr(message$, "Quit")) then
			settingsYabParam$ = textcontrol get$ "RunParamYab"
			settingsProgParam$ = textcontrol get$ "RunParamProg"
			inloop = false
		endif
	wend

	window close "RunParam"
	return
end sub

// load settings on start-up
sub LoadSettings()
	local handle, i, j
	local tmp$

	handle = open(globalConfigDir$+"ide-settings", "r")
	if(not handle) return 1

	while(not eof(handle))
		line input #handle tmp$	
		if(left$(tmp$, 1)<>"#") then
			i = i + 1
			switch(i)
				case 1: settingsYabDir$ = tmp$: break
				case 2: globalProjectDir$ = tmp$: break
				case 3: yabDir$ = tmp$: break
				case 4: ideDir$ = tmp$: break
				case 5: buildDir$ = tmp$: break
				case 6: globalHelpDir$ = tmp$: break
				case 7: settingsLangUse = val(tmp$): break
				case 8: settingsLangPath$ = tmp$: break
				case 9: settingsAutoIndent = val(tmp$): break
				case 10: settingsAutoCompletion = val(tmp$): break
				case 11: settingsACNumChar = val(tmp$): break
				case 12: settingsX = val(tmp$): break
				case 13: settingsY = val(tmp$): break
				case 14: settingsWidth = val(tmp$): break
				case 15: settingsHeight = val(tmp$): break
				case 16: settingsFullScreen = val(tmp$): break
				case 17: settingsFullEditor = val(tmp$): break
				case 18: settingsVSplitDivider  = val(tmp$): break
				case 19: settingsV2SplitDivider  = val(tmp$): break
				case 20: settingsHSplitDivider  = val(tmp$): break
				case 21: settingsCalcPatternX = val(tmp$): break
				case 22: settingsCalcPatternY = val(tmp$): break
				case 23: settingsColorSelectX = val(tmp$): break
				case 24: settingsColorSelectY = val(tmp$): break
				case 25: settingsColorSelectR = val(tmp$): break
				case 26: settingsColorSelectG = val(tmp$): break
				case 27: settingsColorSelectB = val(tmp$): break
				case 28: settingsAskForSaving = val(tmp$): break
				case 29: settingsFindCS = val(tmp$): break
				case 30: settingsOldSearch$ = tmp$: break
				case 31: settingsFindAlert = val(tmp$): break
				case 32: settingsReformatAlert = val(tmp$): break
				case 33: settingsReformatUndoAlert = val(tmp$): break
				case 34: settingsTabSpaces = val(tmp$): break
				case 35: break
				case 36: settingsFontFamily$ = tmp$: break
				case 37: settingsFontStyle$ = tmp$: break
				case 38: settingsFontSize = val(tmp$): break
				case 39: globalRealFontSize = val(tmp$): break
				case 40: DEBUG = val(tmp$): break
				case 41: MAXFILES = val(tmp$): break
				case 42: settingsYabParam$ = tmp$: break
				case 43: settingsProgParam$ = tmp$: break
			end switch
		endif
	wend
	close(handle)

	dim globalAllNames$(MAXFILES)
	dim globalTextFinder(MAXFILES)

	for j=1 to MAXFILES
		globalAllNames$(j) = ""
		globalTextFinder(j) = 0
	next j

	if(i = 43) return 0
	return 1
end sub

// load last opened files on start-up
sub LoadOpenFiles()
	local handle, mainhandle, j, t
	local text$, t$

	mainhandle = open(globalConfigDir$+"ide-openfiles", "r")
	if(mainhandle) then
		j = 1
		while(not eof(mainhandle) and j<=MAXFILES)
			globalAllNames$(j) = GetLine$(mainhandle)
			handle = open(globalAllNames$(j), "r")
			if(handle) then
				WaitWindow(globalAllNames$(j))
				text$ = ""
				while(not eof(handle))
					t$ = GetLine$(handle)+"\n"
					if(len(t$)*8>4000) textedit set "Text"+str$(j), "textwidth", len(t$)*8+8
					text$ = text$ + t$
				wend
				close(handle)
				globalCurrentText = j
				textedit add "Text"+str$(globalCurrentText), text$
				textedit set "Text"+str$(globalCurrentText), "changed", false
				textedit set "Text"+str$(globalCurrentText), "gotoline", ReadLineFromAttr(globalAllNames$(j))
				stackview set "Stack", globalCurrentText
				stackview set "Lines", globalCurrentText
				t = columnbox count "FileBox" 
				columnbox add "FileBox", 1, t+1,20, "__Mime__=application/x-vnd.yab-app"
				columnbox add "FileBox", 2, t+1,20, GetFileName$(globalAllNames$(j)) //  "Filename", t, GetFileName$(tmp$)
				columnbox select "FileBox", t+1
				globalTextFinder(globalCurrentText) = t+1
				option set "Text"+str$(globalCurrentText), "focus", true
				oldScroll = -1
				globalNumOpenFiles = globalNumOpenFiles + 1
				if(globalNumOpenFiles = 1) then
					ActivateMenus(true)
					splitview set "V2Split", "Divider", settingsV2SplitDivider
				endif
				window close "WaitWindow"
			else
				globalAllNames$(j) = ""
			endif
			j = j + 1
		wend
		close(mainhandle)
	endif

	return
end sub

// Export as HTML
sub ExportAsHTML()
	local browse$

	browse$ = filepanel "Save-File", "Export as HTML", globalProjectDir$
	if(browse$<>"") then

		handle = open(browse$, "w")
        	if(handle) then
			print #handle "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">"
			print #handle "<html>"
			print #handle "  <head>"
			print #handle "    <title>" + GetFileName$(globalAllNames$(globalCurrentText)) + "</title>"
			print #handle "    <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">"
			print #handle "    <meta name=\"generator\" content=\"yab-IDE\">"
			print #handle "  </head>"
			print #handle "  <body>"
			print #handle "    <pre>"
        		print #handle textedit get$ "Text"+str$(globalCurrentText);
			print #handle "    </pre>"
			print #handle "  </body>"
			print #handle "</html>"
        		close(handle)
		else
			alert "File could not be saved!", "Ok", "warning"
			return false
		endif
	endif
end sub

// Save all settings before exiting
sub SaveSettings()
	local handle, i

	if(system("test -d "+globalConfigDir$) = 1) then
		system("mkdir "+left$(globalConfigDir$, len(globalConfigDir$)-1))
	endif

	handle = open(globalConfigDir$+"ide-settings", "w")
	if(handle) then
		print #handle "# yab IDE 2.2 config file"
		print #handle "# "
		print #handle "# Comments start with a # as first character on a line"
		print #handle "# Only change this file when you know what you are doing!"
		print #handle "# Do not change the order of the lines in this file!"
		print #handle "# "
		print #handle "# yab directory (ends on /)"
		print #handle settingsYabDir$
		print #handle "# Program directory (ends on /)"
		print #handle globalProjectDir$
		print #handle "# yab binary location"
		print #handle yabDir$
		print #handle "# IDE directory (ends on /)"
		print #handle ideDir$
		print #handle "# BuildFactory directory (ends on /)"
		print #handle buildDir$
		print #handle "# Help directory (ends on /)"
		print #handle globalHelpDir$
		print #handle "# Use localization (0 = false, 1 = true)"
		print #handle restartSettingsLangUse
		print #handle "# localization mimetype"
		print #handle settingsLangPath$
		print #handle "# Auto indent (0 = false, 1 = true)"
		print #handle settingsAutoIndent
		print #handle "# Auto completion (0 = false, 1 = true)"
		print #handle settingsAutoCompletion
		print #handle "# Auto completion starts at character count:"
		print #handle settingsACNumChar
		print #handle "# X-coordinates of main window"
		print #handle settingsX
		print #handle "# Y-coordinates of main window"
		print #handle settingsY
		print #handle "# Width of main window"
		print #handle settingsWidth
		print #handle "# Height of main window"
		print #handle settingsHeight
		print #handle "# Start in fullscreen (0 = false, 1 = true)"
		print #handle settingsFullScreen
		print #handle "# Start in maximized editor (0 = false, 1 = true)"
		print #handle settingsFullEditor
		print #handle "# Position of main vertical divider"
		print #handle settingsVSplitDivider 
		print #handle "# Position of the vertical divider for the line numbers"
		print #handle settingsV2SplitDivider 
		print #handle "# Position of main horizontal divider"
		print #handle settingsHSplitDivider 
		print #handle "# X-coordinate of the pattern editor window"
		print #handle settingsCalcPatternX
		print #handle "# Y-coordinate of the pattern editor window"
		print #handle settingsCalcPatternY
		print #handle "# X-coordinate of the color selection window"
		print #handle settingsColorSelectX
		print #handle "# Y-coordinate of the color selection window"
		print #handle settingsColorSelectY
		print #handle "# Red value for last selected color in color selection window"
		print #handle settingsColorSelectR
		print #handle "# Green value for last selected color in color selection window"
		print #handle settingsColorSelectG
		print #handle "# Blue value for last selected color in color selection window"
		print #handle settingsColorSelectB
		print #handle "# Ask for saving before running a program (0 = false, 1 = true)"
		print #handle settingsAskForSaving
		print #handle "# Is \"find\" case sensitive? (0 = false, 1 = true)"
		print #handle settingsFindCS
		print #handle "# Last search string"
		print #handle settingsOldSearch$
		print #handle "# Show warning before applying Replace All (0 = false, 1 = true)"
		print #handle settingsFindAlert
		print #handle "# Show warning when reformating sourcecode did not close all loops and conditions (0 = false, 1 = true)"
		print #handle settingsReformatAlert
		print #handle "# Show warning before undo reformating (0 = false, 1 = true)"
		print #handle settingsReformatUndoAlert
		print #handle "# Number of spaces per tab"
		print #handle settingsTabSpaces
		print #handle "# Unused field (was: use Haiku tabs on ZETA)."
		print #handle 0
		print #handle "# Font family name"
		print #handle settingsFontFamily$
		print #handle "# Font style"
		print #handle settingsFontStyle$
		print #handle "# Font size"
		print #handle settingsFontSize
		print #handle "# Real font size"
		print #handle globalRealFontSize
		print #handle "# Print out IDE debug information (0 = false, 1 = true)" 
		print #handle DEBUG
		print #handle "# Maximum number of files the IDE can handle" 
		print #handle MAXFILES
		print #handle "# yab runtime parameters (default is empty)"
		print #handle settingsYabParam$
		print #handle "# Program runtime parameters (default is empty)"
		print #handle settingsProgParam$

		close(handle)
	endif

	handle = open(globalConfigDir$+"ide-openfiles", "w")
	if(handle) then
		for i=1 to MAXFILES
			if(globalAllNames$(i)<>"") print #handle globalAllNames$(i)
		next i
		close(handle)
	endif
	return
end sub

sub path()
path$=attribute get$ "" , "" 
path$=path$+"/"
end sub


sub yabpath$()

if system("test -e /boot/home/config/non-packaged/bin/yab") = 0 then
	return "/boot/home/config/non-packaged/bin/yab"
elseif system("test -e /boot/home/config/bin/yab") = 0 then
 		return "/boot/home/config/bin/yab"
elseif system("test -e /boot/system/bin/yab") = 0 then
 		return "/boot/system/bin/yab"

endif

local cmd$
cmd$="test -e "+settingsYabDir$
if system(cmd$)=0 then 
	return settingsYabDir$
endif

return "error"
end sub

sub set_up_BuildFactory()
local DataDir$
local x
local y
local handel
local ddir$

DataDir$=trim$(system$("finddir  B_USER_DIRECTORY"))
x=system("mkdir "+DataDir$+"/yab_work")
system("mkdir ~/config/settings/yab")
y=system("ls "+DataDir$+"/yab_work/BuildFactory > /dev/null")
y=y+system("ls "+DataDir$+"/yab_work/Programs > /dev/null")
system("cp -ur "+ideDir$+"BuildFactory "+DataDir$+"/yab_work")
handle=open(DataDir$+"/yab_work/BuildFactory/srcfiles","r")

		while(not eof(#handle)) 
			input #handle a$ 
			system("cp -u "+ideDir$+"src/"+a$+" "+DataDir$+"/yab_work/BuildFactory/"+a$)
		end while
	close handle
	system("cp -ur "+ideDir$+"src/column "+DataDir$+"/yab_work/BuildFactory")

if x=0  or y>0 then

	system("cp -ur "+ideDir$+"BuildFactory "+DataDir$+"/yab_work")
	system("cp -ur "+ideDir$+"Programs "+DataDir$+"/yab_work")
	system ("cp -ur "+ideDir$+"img "+DataDir$+"/yab_work/Programs")
	system("cp -ur "+ideDir$+"Programs/libs/* /boot/home/config/settings/yab")

	handle=open(DataDir$+"/yab_work/BuildFactory/srcfiles","r")

		while(not eof(#handle)) 
			input #handle a$ 
			system("cp -u "+ideDir$+"src/"+a$+" "+DataDir$+"/yab_work/BuildFactory/"+a$)
		end while
	close handle

	system("cp -ur "+ideDir$+"src/column "+DataDir$+"/yab_work/BuildFactory")
end if

x=1
open #1, ideDir$+"src/YabMain.cpp","r"
open #2, DataDir$+"/yab_work/BuildFactory/parts/YabMain.cpp.end","w"

while(not eof(#1)) 
	line input #1 a$
	if x>9  then 
	print #2 a$
	end if
	x=x+1
wend 
close #1
close #2

end sub
	



sub changestring()

TextLine$ = TEXTEDIT GET$"Text"+str$(globalCurrentText), searchLineNum
TextLine$=rtrim$(TextLine$ )						
FindPart$=textcontrol get$ "FindTCFind"
FindPart$=trim$(FindPart$)
if(settingsFindCS) then
	x=instr(TextLine$, FindPart$)
else
	x=instr(upper$(TextLine$), upper$(FindPart$))

endif
if x>0 then
	x=x-1
	TextPart$= textcontrol get$ "FindTCReplace"
	TextPart$=rtrim$(TextPart$)
	TextLine$=left$(TextLine$,x)+TextPart$+right$(TextLine$,len(TextLine$)-(x+(len(FindPart$))))
	TEXTEDIT SET "Text"+str$(globalCurrentText), "select", searchLineNum
	TEXTEDIT SET "Text"+str$(globalCurrentText), "cut"
	TEXTEDIT SET "Text"+str$(globalCurrentText), "select", searchLineNum
	TEXTEDIT ADD "Text"+str$(globalCurrentText), TextLine$
	TEXTEDIT SET "Text"+str$(globalCurrentText), "gotoline", searchLineNum
	searchLineNum = textedit get "Text"+str$(globalCurrentText), "Find", TextPart$ 

endif

end sub

sub getappsig$(infil$)
local x,a$,i,ii
open #122,infil$,"r" 
for i=1 to 2
line input #122 a$
a$=lower$(a$)
ii = instr(a$,"mimetype")
if ii<>0 then
a$=right$(a$,len(a$) - (ii+8))
a$=trim$(a$)
a$=right$(a$,len(a$)-1)
a$=left$(a$,len(a$)-1)
close #122
return a$
endif
next
close #122
return ""


end sub


sub getprojectdir$()
local CurrentSelection, CurrentSelection$, i,OpenProjectDir$
CurrentSelection = columnbox get "FileBox"
CurrentSelection$ = columnbox get$ "FileBox", 2, CurrentSelection
for i=1 to COLUMNBOX COUNT "FileBox"
if (GetFileName$(globalAllNames$(i)) = CurrentSelection$) OpenProjectDir$ =  GetDirectory$(globalAllNames$(i)):break
next
return OpenProjectDir$
end sub
