#!/data/data/com.termux/files/usr/bin/python
import tkinter as tk
from tkinter import messagebox
import config
import sys  # For passing the Project index as an argument

class Application (tk.Frame):
	def __init__ (self, master = None):
		tk.Frame.__init__ (self, master)
		self.grid (sticky = tk.N + tk.S + tk.E + tk.W)
		# I'm leaving this here in case I want to draw a background image in the future.
		#self.imgBackground = tk.PhotoImage(file=config.defaultimage0)
		#self.lblBackground = tk.Label(self, image=self.imgBackground)
		#self.lblBackground.place(x=0, y=0, relwidth=1, relheight=1)
		self.createWidgets()
		# New in July 2025 - can run make.sh with the index of the Project as an argument, so you don't have to scroll through the list every time you want to Make.
		if len (sys.argv) > 1:  # Is an argument being passed?
			self.cboProject.select_set (int (sys.argv [1]))
			self.cboProject.see (int (sys.argv [1] [0]) + 20)  # Scroll so the selected Project is near the top of the view.
			self.getscreenshot (None)  # Still need to call getscreenshot with no event.

	def createWidgets (self):
		top = self.winfo_toplevel()
		top.rowconfigure (0, weight = 1)
		top.columnconfigure (0, weight = 1)
		self.rowconfigure (0, weight = 1)
		self.columnconfigure (0, weight = 1)

		# I kept the excess commenting in pidejl.py, in case you want to know how this code works.  It's very similar to this.
		self.yScroll = tk.Scrollbar (self, width = 24, orient = tk.VERTICAL)
		self.yScroll.grid (row = 0, column = 2, rowspan = 4, sticky = tk.N + tk.S)

		ProjectNames = []  # List of the projects
		for Project in config.ProjectList:
			ProjectNames.append (Project [0])
		self.varProject = tk.StringVar()
		self.varProject.set (ProjectNames)
		self.cboProject = tk.Listbox (self, font = config.font, bg = config.colormenusbg, fg = config.colormenusfg, width = config.listwidth, yscrollcommand = self.yScroll.set, listvariable = self.varProject)
		self.cboProject.grid (row = 0, column = 1, rowspan = 4, sticky = tk.N + tk.S)
		self.yScroll ["command"] = self.cboProject.yview
		self.cboProject.bind ("<<ListboxSelect>>", self.getscreenshot)

		self.imgScreenshot = tk.PhotoImage (file = config.defaultimage1)
		self.lblScreenshot = tk.Label (self, image = self.imgScreenshot)
		self.lblScreenshot.grid (row = 0, column = 0)

		self.frameGraphicsOptions = tk.LabelFrame (self, font = config.fontframeheader, labelanchor = "n", text = "Display Options", bg = config.colorpanelsbg)
		self.frameGraphicsOptions.grid (row = 1, column = 0, rowspan = 2)

		self.frameSoundOptions = tk.LabelFrame (self, font = config.fontframeheader, labelanchor = "n", text = "Audio Options", bg = config.colorpanelsbg)
		self.frameSoundOptions.grid (row = 3, column = 0, sticky = tk.S + tk.E + tk.W)

		self.frameCommands = tk.LabelFrame (self, font = config.fontframeheader, labelanchor = "n", text = "Commands", bg = config.colorpanelsbg)
		self.frameCommands.grid (row = 0, column = 3)

		self.frameSystemOptions = tk.LabelFrame (self, font = config.fontframeheader, labelanchor = "n", text = "System Options", bg = config.colorpanelsbg)
		self.frameSystemOptions.grid (row = 1, column = 3, sticky = tk.N + tk.E + tk.W)

		self.framePeripheralOptions = tk.LabelFrame (self, font = config.fontframeheader, labelanchor = "n", text = "Peripheral Options", bg = config.colorpanelsbg)
		self.framePeripheralOptions.grid (row = 2, column = 3, sticky = tk.N + tk.E + tk.W)

		self.frameGeneralOptions = tk.LabelFrame (self, font = config.fontframeheader, labelanchor = "n", text = "Other Options", bg = config.colorpanelsbg)
		self.frameGeneralOptions.grid (row = 3, column = 3, sticky = tk.S + tk.E + tk.W)

		self.cmdEdit = tk.Button (self.frameCommands, font = config.font, text = "Edit", bg = config.colormenusbg, width = 6, disabledforeground = "black", fg = config.colormenusfg, state = tk.DISABLED, command = self.doedit)  # The Edit button.  All buttons except Quit are greyed-out to begin with.
		self.cmdEdit.grid (row = 0, column = 0, sticky = tk.E + tk.W)

		self.cmdMake = tk.Button (self.frameCommands, font = config.font, text = "Make", bg = config.colormenusbg, width = 6, disabledforeground = "black", fg = config.colormenusfg, state = tk.DISABLED, command = self.domake)  # The Make button.
		self.cmdMake.grid (row = 1, column = 0, sticky = tk.E + tk.W)

		self.cmdBackup = tk.Button (self.frameCommands, font = config.font, text = "Backup", bg = config.colormenusbg, width = 6, disabledforeground = "black", fg = config.colormenusfg, state = tk.DISABLED, command = self.dobackup)  # The Backup button.
		self.cmdBackup.grid (row = 2, column = 0, sticky = tk.E + tk.W)

		self.cmdRun = tk.Button (self.frameCommands, font = config.font, text = "Play", bg = config.colormenusbg, width = 6, disabledforeground = "black", fg = config.colormenusfg, state = tk.DISABLED, command = self.dorun)  # The Play button.
		self.cmdRun.grid (row = 0, column = 1, sticky = tk.E + tk.W)

		self.cmdAbout = tk.Button (self.frameCommands, font = config.font, text = "About", bg = config.colormenusbg, width = 6, fg = config.colormenusfg, command = self.doabout)  # The About button.
		self.cmdAbout.grid (row = 1, column = 1, sticky = tk.E + tk.W)

		self.cmdQuit = tk.Button (self.frameCommands, font = config.font, text = "Quit", bg = config.colormenusbg, width = 6, fg = config.colormenusfg, command = self.doquit)  # The Quit button.
		self.cmdQuit.grid (row = 2, column = 1, sticky = tk.E + tk.W)

		self.varIntellivoice = tk.IntVar()
		self.chkIntellivoice = tk.Checkbutton (self.framePeripheralOptions, font = config.font, text = "IntelliVoice", bg = config.colorpanelsbg, variable = self.varIntellivoice, offvalue = 0, onvalue = 1)
		self.chkIntellivoice.grid (row = 0, sticky = tk.W)
		#self.chkIntellivoice.deselect()

		self.varECS = tk.IntVar()
		self.chkECS = tk.Checkbutton (self.framePeripheralOptions, font = config.font, text = "ECS", bg = config.colorpanelsbg, variable = self.varECS, offvalue = 0, onvalue = 1)
		self.chkECS.grid (row = 1, sticky = tk.W)
		#self.chkECS.deselect()

		self.varBorderSize = tk.IntVar()
		self.varBorderSize.set (config.defaultbordersize)
		self.validation = self.register (self.onlydigits)
		self.lblBorderSize = tk.Label (self.frameGraphicsOptions, font = config.font, text = "Border Size: ", bg = config.colorpanelsbg)
		self.lblBorderSize.grid (row = 4, column = 0, columnspan = 4, pady = 10, sticky = tk.E + tk.S)

		self.txtBorderSize = tk.Entry (self.frameGraphicsOptions, font = config.font, textvariable = self.varBorderSize, validate = "key", validatecommand = (self.validation, "%P"), width = 2)
		self.txtBorderSize.grid (row = 4, column = 4, columnspan = 2, pady = 10, sticky = tk.W + tk.S)

		self.varDisplayOption = tk.IntVar()
		self.varDisplayOption.set (config.defaultdisplayoption)
		self.chkDisplayOption0 = tk.Radiobutton (self.frameGraphicsOptions, font = config.font, text = "Pre-defined size:", bg = config.colorpanelsbg, variable = self.varDisplayOption, value = 0)  # There is only one value this time, the value when checked, analagous to the checkbutton's onvalue.
		self.chkDisplayOption0.grid (row = 0, column = 0, columnspan = 6, sticky = tk.W)
		self.chkDisplayOption1 = tk.Radiobutton (self.frameGraphicsOptions, font = config.font, text = "Custom size:", bg = config.colorpanelsbg, variable = self.varDisplayOption, value = 1)
		self.chkDisplayOption1.grid (row = 2, column = 0, columnspan = 6, sticky = tk.W)

		self.varDisplaySize = tk.IntVar()
		self.varDisplaySize.set (config.defaultwindowsize)
		self.varDisplaySizeName = tk.StringVar()
		self.varDisplaySizeName.set (config.DisplaySizeList [config.defaultwindowsize])
		self.optDisplaySize = tk.OptionMenu (self.frameGraphicsOptions, self.varDisplaySizeName, *config.DisplaySizeList, command = self.setdisplaysize)
		self.optDisplaySize.config (font = config.fontoptionmenu, bg = config.colormenusbg, fg = config.colormenusfg)
		self.optDisplaySize ["menu"].config (font = config.fontoptionmenu, bg = config.colormenusbg, fg = config.colormenusfg)
		self.optDisplaySize.grid (row = 1, column = 0, columnspan = 6)

		self.varDisplayResX = tk.IntVar()
		self.varDisplayResX.set (config.defaultwindowresx)
		self.lblDisplayResX = tk.Label (self.frameGraphicsOptions, font = config.font, text = "x", bg = config.colorpanelsbg)
		self.lblDisplayResX.grid (row = 3, column = 1, pady = 10, sticky = tk.S)
		self.txtDisplayResX = tk.Entry (self.frameGraphicsOptions, font = config.font, textvariable = self.varDisplayResX, validate = "key", validatecommand = (self.validation, "%P"), width = 4)
		self.txtDisplayResX.grid (row = 3, column = 0, pady = 10, sticky = tk.E + tk.S)
		self.varDisplayResY = tk.IntVar()
		self.varDisplayResY.set (config.defaultwindowresy)
		self.lblDisplayResY = tk.Label (self.frameGraphicsOptions, font = config.font, text = ", ", bg = config.colorpanelsbg)
		self.lblDisplayResY.grid (row = 3, column = 3, pady = 10, sticky = tk.S)
		self.txtDisplayResY = tk.Entry (self.frameGraphicsOptions, font = config.font, textvariable = self.varDisplayResY, validate = "key", validatecommand = (self.validation, "%P"), width = 4)
		self.txtDisplayResY.grid (row = 3, column = 2, pady = 10, sticky = tk.S)

		self.varDisplayBPP = tk.IntVar()
		self.varDisplayBPP.set (config.defaultwindowbitdepth)
		self.lblDisplayBPP = tk.Label (self.frameGraphicsOptions, font = config.font, text = "bpp", bg = config.colorpanelsbg)
		self.lblDisplayBPP.grid (row = 3, column = 5, pady = 10, sticky = tk.W + tk.S)
		self.txtDisplayBPP = tk.Spinbox (self.frameGraphicsOptions, font = config.font, from_= 8, to = 32, increment = 8, bd = 0, relief = tk.SOLID, width = 2, command = self.selectcustom)
		self.txtDisplayBPP.grid (row = 3, column = 4, pady = 10, sticky = tk.S)
		self.txtDisplayBPP.delete (0, "end")
		self.txtDisplayBPP.insert (0, str (config.defaultwindowbitdepth))

		self.varFullscreen = tk.IntVar()
		self.varFullscreen.set (config.defaultfullscreen)
		self.chkWindowed = tk.Radiobutton (self.frameGraphicsOptions, font = config.font, text = "Windowed", bg = config.colorpanelsbg, variable = self.varFullscreen, value = 0)
		self.chkWindowed.grid (row = 5, column = 0, columnspan = 4, sticky = tk.W)
		self.chkFullscreen = tk.Radiobutton (self.frameGraphicsOptions, font = config.font, text = "Full Screen", bg = config.colorpanelsbg, variable = self.varFullscreen, value = 1)
		self.chkFullscreen.grid (row = 6, column = 0, columnspan = 4, sticky = tk.W)

		self.varMode = tk.StringVar()
		self.varMode.set (config.defaultgraphicsmode)
		self.chkNTSC = tk.Radiobutton (self.frameGraphicsOptions, font = config.font, text = "NTSC", bg = config.colorpanelsbg, variable = self.varMode, value = " ")
		self.chkNTSC.grid (row = 5, column = 4, columnspan = 2, sticky = tk.W)
		self.chkPAL = tk.Radiobutton (self.frameGraphicsOptions, font = config.font, text = "PAL", bg = config.colorpanelsbg, variable = self.varMode, value = "-P")
		self.chkPAL.grid (row = 6, column = 4, columnspan = 2, sticky = tk.W)

		self.varAudioRate = tk.IntVar()
		self.varAudioRate.set (config.defaultaudiorate)
		self.chkAudioNone = tk.Radiobutton (self.frameSoundOptions, font = config.font, text = "No sound", bg = config.colorpanelsbg, variable = self.varAudioRate, value = 0)
		self.chkAudioNone.grid (row = 0, column = 0, sticky = tk.W)
		self.chkAudioLow = tk.Radiobutton (self.frameSoundOptions, font = config.font, text = "Better performance", bg = config.colorpanelsbg, variable = self.varAudioRate, value = 11025)
		self.chkAudioLow.grid (row = 1, column = 0, sticky = tk.W)
		self.chkAudioHigh = tk.Radiobutton (self.frameSoundOptions, font = config.font, text = "Better quality", bg = config.colorpanelsbg, variable = self.varAudioRate, value = 48000)
		self.chkAudioHigh.grid (row = 2, column = 0, sticky = tk.W)

		self.varExec = tk.StringVar()
		self.varExec.set (config.ExecList [config.defaultexec] [0])
		self.varExecIndex = tk.IntVar()
		self.varExecIndex.set (config.defaultexec)
		self.varExec.set (config.ExecList [self.varExecIndex.get()] [0])  # Name of the Executive ROM to be displayed by default
		self.lblExec = tk.Label (self.frameSystemOptions, font = config.font, text = "Executive ROM:", bg = config.colorpanelsbg)
		self.lblExec.grid (row = 0, sticky = tk.W)
		# We need to build this list before constructing the Exec OptionMenu.
		self.ExecNames = []  # Start with a blank list.
		for Exec in config.ExecList:  # Iterate through the ExecList in config.py.
			self.ExecNames.append (Exec [0])  # Fetch the name, the first element (index 0).
		self.optExec = tk.OptionMenu (self.frameSystemOptions, self.varExec, *self.ExecNames, command = self.setexec)
		self.optExec.config (font = config.fontoptionmenu, bg = config.colormenusbg, fg = config.colormenusfg)
		self.optExec ["menu"].config (font = config.fontoptionmenu, bg = config.colormenusbg, fg = config.colormenusfg)
		self.optExec.grid (row = 1, sticky = tk.W + tk.E)

		self.varGROM = tk.StringVar()
		self.varGROM.set (config.GROMList [config.defaultgrom] [0])
		self.varGROMIndex = tk.IntVar()
		self.varGROMIndex.set (config.defaultgrom)
		self.varGROM.set (config.GROMList [self.varGROMIndex.get()] [0])
		self.lblGROM = tk.Label (self.frameSystemOptions, font = config.font, text = "Graphics ROM:", bg = config.colorpanelsbg)
		self.lblGROM.grid (row = 2, sticky = tk.W)
		# Same as with the Exec OptionMenu, we need to build this list.
		self.GROMNames = []
		for GROM in config.GROMList:
			self.GROMNames.append (GROM [0])
		self.optGROM = tk.OptionMenu (self.frameSystemOptions, self.varGROM, *self.GROMNames, command = self.setgrom)
		self.optGROM.config (font = config.fontoptionmenu, bg = config.colormenusbg, fg = config.colormenusfg)
		self.optGROM ["menu"].config (font = config.fontoptionmenu, bg = config.colormenusbg, fg = config.colormenusfg)
		self.optGROM.grid (row = 3, sticky = tk.W + tk.E)

		self.varGRAM = tk.IntVar()
		self.chkGRAM0 = tk.Radiobutton (self.frameGeneralOptions, font = config.font, text = "Normal GRAM", bg = config.colorpanelsbg, variable = self.varGRAM, value = 0)
		self.chkGRAM0.grid (row = 0, sticky = tk.W)
		self.chkGRAM1 = tk.Radiobutton (self.frameGeneralOptions, font = config.font, text = "Double GRAM", bg = config.colorpanelsbg, variable = self.varGRAM, value = 1)
		self.chkGRAM1.grid (row = 1, sticky = tk.W)
		self.chkGRAM2 = tk.Radiobutton (self.frameGeneralOptions, font = config.font, text = "Quadruple GRAM", bg = config.colorpanelsbg, variable = self.varGRAM, value = 2)
		self.chkGRAM2.grid (row = 2, sticky = tk.W)
		#self.chkGRAM0.select()

		self.varTutorVision = tk.BooleanVar()
		self.chkTutorVision = tk.Checkbutton (self.frameGeneralOptions, font = config.font, text = "TutorVision Mode", bg = config.colorpanelsbg, variable = self.varTutorVision, command = lambda: self.tutorvision (None))
		self.chkTutorVision.grid (row = 3, column = 0, sticky = tk.W + tk.S)
		self.varPalette = tk.StringVar()
		self.varPalette.set (config.defaultpalette)
		self.chkPalette = tk.Checkbutton (self.frameGeneralOptions, font = config.font, text = "Custom palette", bg = config.colorpanelsbg, variable = self.varPalette, offvalue = "", onvalue = "--gfx-palette=" + config.workingpath + "intycolors.cfg")
		self.chkPalette.grid (row = 4, column = 0, sticky = tk.W + tk.S)

	# Validation for the Entry box.  We want only numeric characters.
	def onlydigits (self, inp):
		if inp == "":
			return True
		return inp.isdigit()

	# This code fires when the user changes any of the Custom graphics options.
	def selectcustom (self):
		self.chkDisplayOption1.select()  # Automatically check the "Custom" radiobutton.

	# This code fires when the user selects a project from the list.
	def getscreenshot (self, event):
		# The command buttons and GRAM radiobuttons can now be enabled since a project is selected.
		self.cmdEdit.config (state = tk.NORMAL)
		self.cmdMake.config (state = tk.NORMAL)
		self.cmdBackup.config (state = tk.NORMAL)
		self.cmdRun.config (state = tk.NORMAL)
		self.chkGRAM1.config (state = tk.NORMAL)
		self.chkGRAM2.config (state = tk.NORMAL)
		try:
			basefilename = config.projectpath + config.ProjectList [self.cboProject.curselection() [0]] [1] + config.ProjectList [self.cboProject.curselection() [0]] [6]
		except:
			self.cmdEdit.config (state = tk.DISABLED)
			self.cmdMake.config (state = tk.DISABLED)
			self.cmdBackup.config (state = tk.DISABLED)
			self.cmdRun.config (state = tk.DISABLED)
			self.chkGRAM0.select()
			self.chkGRAM1.config (state = tk.DISABLED)
			self.chkGRAM2.config (state = tk.DISABLED)
			print ("Wake up!")
		try:
			self.imgScreenshot.config (file = basefilename + ".gif")
		except:
			self.imgScreenshot.config (file = config.defaultimage2)
		if self.varGRAM.get() == 1:  # Double Graphics RAM, for modified Intellivision II units
			self.varExecIndex.set (2)  # Change the Executive ROM to Intellivision II.
			self.varExec.set (config.ExecList [2] [0])
		elif self.varGRAM.get() == 2:  # Quadruple Graphics RAM, for World Book Tutorvision
			self.varExecIndex.set (3)  # Change the Executive ROM to World Book Tutorvision.
			self.varExec.set (config.ExecList [3] [0])
			self.varGROMIndex.set (1)  # Change the Graphics ROM to INTV88.
			self.varGROM.set (config.GROMList [1] [0])
			self.chkECS.deselect()
			self.chkECS.config (state = tk.DISABLED)  # Can't use ECS with Tutorvision

	# This code fires when the user selects one of the Pre-Defined display sizes from the drop-down menu.
	def setdisplaysize (self, event):
		for index, string in enumerate (config.DisplaySizeList):
			if (self.varDisplaySizeName.get() == string):
				self.varDisplaySize.set (index)
		self.chkDisplayOption0.select()

	# This code fires when the user selects a different Executive ROM from the drop-down menu.
	def setexec (self, event):
		for index, string in enumerate (config.ExecList):
			if (self.varExec.get() == string [0]):
				self.varExecIndex.set (index)
				self.chkECS.config (state = tk.NORMAL)
				if self.varExecIndex.get() == 3:  # Tutorvision Exec?
					self.chkECS.deselect()
					self.chkECS.config (state = tk.DISABLED)  # Can't use ECS with Tutorvision

	# This code fires when the user selects a different Graphics ROM from the drop-down menu.
	def setgrom (self, event):
		for index, string in enumerate (config.GROMList):
			if (self.varGROM.get() == string [0]):
				self.varGROMIndex.set (index)

	# This code fires when the TutorVision Checkbutton is checked.
	def tutorvision (self, event):
		#if tk.messagebox.askyesno ("TutorVision Mode", "Do you also want ECS disabled and extra GRAM?"):
		if self.varTutorVision.get():
			self.varExecIndex.set (3)  # Change the Executive ROM to World Book Tutorvision.
			self.varExec.set (config.ExecList [3] [0])
			self.varGROMIndex.set (1)  # Change the Graphics ROM to INTV88.
			self.varGROM.set (config.GROMList [1] [0])
			self.chkECS.deselect()
			self.chkECS.config (state = tk.DISABLED)
			self.chkGRAM2.select()
			self.chkGRAM0.config (state = tk.DISABLED)
			self.chkGRAM1.config (state = tk.DISABLED)
		else:
			self.chkECS.config (state = tk.NORMAL)
			self.chkGRAM0.config (state = tk.NORMAL)
			#self.chkGRAM0.select()
			self.chkGRAM1.config (state = tk.NORMAL)
			self.varExecIndex.set (config.defaultexec)
			self.varExec.set (config.ExecList [config.defaultexec] [0])
			self.varGROMIndex.set (config.defaultgrom)
			self.varGROM.set (config.GROMList [config.defaultgrom] [0])

	# This code fires when the Edit button is clicked.
	def doedit (self):
		file.write (config.editor)
		for Files in config.ProjectList [self.cboProject.curselection() [0]] [2]:
			file.write (" " + config.projectpath + config.ProjectList [self.cboProject.curselection() [0]] [1] + Files)
		file.write ("& \n")
		file.write ("make " + sys.argv [1] + " &\n" if len (sys.argv) > 1 else "make &\n")  # Re-launch this application.
		file.close()
		self.quit()

	# This code fires when the Make button is clicked.
	def domake (self):
		file.write ("echo -e ${White}Step 1, Compiling the code.${NoColor}\n")
		file.write ("DrawThatLine\n")
		file.writelines (["intybasic_termux",
			" --title \"" + config.ProjectList [self.cboProject.curselection() [0]] [0] + "\"",  # The game title, encapsulated in quotes
			" " + config.ProjectList [self.cboProject.curselection() [0]] [4],  # JLP?
			" " + config.projectpath + config.ProjectList [self.cboProject.curselection() [0]] [1] + config.ProjectList [self.cboProject.curselection() [0]] [5],  # Full path to the main source file
			" " + config.projectpath + config.ProjectList [self.cboProject.curselection() [0]] [1] + config.ProjectList [self.cboProject.curselection() [0]] [6] + ".asm\n"])  # Full path to the assembly file to be created
		file.write ("var=$?\n")  # Find out whether compilation was a success or failure.
		file.write ("DrawThatLine\n")
		file.write ("echo IntyBASIC returned exit status $var\n")
		file.write ("if [ $var -ne 0 ] ; then\n")
		file.write ("\techo -e That means ${LightRed}compilation failed${NoColor}.  Goodbye.\n")
		file.write ("else\n")
		file.write ("\techo -e That means ${LightGreen}compilation was successful${NoColor}.\n")
		file.write ("\techo -e So, on to ${White}Step 2, Creating the ROM image.${NoColor}\n")
		file.write ("\tDrawThatLine\n")
		file.write ("\techo\n")
		file.writelines (["\tas1600",
			" -j " + config.projectpath + config.ProjectList [self.cboProject.curselection() [0]] [1] + config.ProjectList [self.cboProject.curselection() [0]] [6] + ".smap",  # Debugger files
			" -s " + config.projectpath + config.ProjectList [self.cboProject.curselection() [0]] [1] + config.ProjectList [self.cboProject.curselection() [0]] [6] + ".sym",
			" -l " + config.projectpath + config.ProjectList [self.cboProject.curselection() [0]] [1] + config.ProjectList [self.cboProject.curselection() [0]] [6] + ".lst",
			" -o " + config.projectpath + config.ProjectList [self.cboProject.curselection() [0]] [1] + config.ProjectList [self.cboProject.curselection() [0]] [6] + ".bin",  # Full path to the ROM image file to be created
			" " + config.projectpath + config.ProjectList [self.cboProject.curselection() [0]] [1] + config.ProjectList [self.cboProject.curselection() [0]] [6] + ".asm\n"])
		file.write ("\tvar=$?\n")
		file.write ("\techo\n")
		file.write ("\tDrawThatLine\n")
		file.write ("\techo as1600 returned exit status $var\n")
		file.write ("\tif [ $var -ne 0 ] ; then\n")
		file.write ("\t\techo -e That means ${LightRed}assembly failed${NoColor}.  Goodbye.\n")
		file.write ("\telse\n")
		file.write ("\t\techo -e That means ${LightGreen}assembly was successful${NoColor}.\n")
		file.write ("\t\techo -e So, ${White}Final Step, Displaying the Config file, and outputting the final product.${NoColor}\n")
		file.write ("\t\tDrawThatLine\n")
		file.write ("\t\techo\n")
		file.write ("\t\tcat " + config.projectpath + config.ProjectList[self.cboProject.curselection() [0]] [1] + config.ProjectList [self.cboProject.curselection() [0]] [6] + ".cfg\n")  # Display .cfg file contents.
		file.write ("\t\tcp " + config.projectpath + config.ProjectList[self.cboProject.curselection() [0]] [1] + config.ProjectList [self.cboProject.curselection() [0]] [6] + ".* \"" + config.archivepath + config.ProjectList [self.cboProject.curselection() [0]] [3] + "\"\n")  # Copy the source files to the archivepath.
		file.write ("\t\tcp " + config.projectpath + config.ProjectList[self.cboProject.curselection() [0]] [1] + config.ProjectList [self.cboProject.curselection() [0]] [6] + ".bin \"" + config.rompath + "\"\n")  # Copy the object files to the rompath.
		file.write ("\t\tcp " + config.projectpath + config.ProjectList[self.cboProject.curselection() [0]] [1] + config.ProjectList [self.cboProject.curselection() [0]] [6] + ".cfg \"" + config.rompath + "\"\n")
		file.write ("\tfi\n")
		file.write ("fi\n")
		file.write ("make " + sys.argv [1] + " &\n" if len (sys.argv) > 1 else "make &\n")  # Re-launch this application.
		file.close()
		self.quit()

	# This code fires when the Backup button is clicked.
	def dobackup (self):
		for Files in config.ProjectList [self.cboProject.curselection() [0]] [2]:
			file.write ("cp " + config.projectpath + config.ProjectList [self.cboProject.curselection() [0]] [1] + Files + " \"" + config.archivepath + config.ProjectList [self.cboProject.curselection() [0]] [3] + "\"\n")
		file.write ("echo Backed up source files for \"" + config.ProjectList [self.cboProject.curselection() [0]] [0] + "\".\n")
		file.write ("make " + sys.argv [1] + " &\n" if len (sys.argv) > 1 else "make &\n")  # Re-launch this application.
		file.close()
		self.quit()

	# This code fires when the Play button is clicked.
	def dorun (self):
		basefilename = config.projectpath + config.ProjectList [self.cboProject.curselection() [0]] [1] + config.ProjectList [self.cboProject.curselection() [0]] [6]  # Fetch the path and ROM image filename.
		file.write ("if [ -e \"" + basefilename + ".png\" ] ; then\n")  # Check for an existing box image.
		#file.write ("\tfeh --bg-max \"" + config.boxpath + basefilename + ".png\"\n")
		file.write ("\tfeh --no-fehbg -x -F -Z \"" + basefilename + ".png\" &\n")
		file.write ("\tsleep 1\n")  # Need to add a one-second delay so the box image doesn't pop up on top of the overlay image.
		file.write ("fi\n")
		file.write ("if [ -e \"" + basefilename + ".pdf\" ] ; then\n")  # Check for an existing instruction manual.
		file.write ("\txpdf -geometry -0+0 \"" + basefilename + ".pdf\" &\n")  # If found, draw it as a pop-up window on the top right corner of the screen.
		file.write ("\tsleep 1\n")  # Need to add a one-second delay here as well.
		file.write ("fi\n")
		file.write ("if [ -e \"" + basefilename + ".jpg\" ] ; then\n")  # Check for an existing overlay image.
		file.write ("\tfeh --no-fehbg --zoom fill -x -g +0+0 \"" + basefilename + ".jpg\" &\n")
		file.write ("fi\n")
		# Now for the call to jzintv.
		file.writelines ([config.jzintvpath + "jzintv",
			" \"" + basefilename + ".bin\"",  # The ROM image file, encapsulated in quotes.
			" " + config.globaloptions,  # The global options will come first, so anything game-specific can override them.
			" --src-map=\"" + basefilename+ ".smap\"",
			" --sym-file=\"" + basefilename+ ".sym\"",
			{True: " --jlp-savegame=" + basefilename + ".sav", False: ""} [config.ProjectList [self.cboProject.curselection() [0]] [4] == "--jlp"],  # Use JLP?
			#" " + self.varGROM.get(),  # TutorVision?
			" " + self.varPalette.get(),  # Use custom palette?
			" " + self.varMode.get(),  # NTSC or PAL?
			" -s" + str (self.varECS.get()),  # ECS or no?
			" -v" + str (self.varIntellivoice.get()),  # IntelliVoice or no?
			" -G" + str (self.varGRAM.get()),  # The usual amount of GRAM or more?
			" --displaysize=" + str (self.varDisplayResX.get()) + "x" + str (self.varDisplayResY.get()) + "," + str (self.varDisplayBPP.get()) if self.varDisplayOption.get() else " -z" + str(self.varDisplaySize.get()),  # Display size and bit depth
			" -f" + str (self.varFullscreen.get()),  # Fullscreen?
			" -b" + str (self.varBorderSize.get()),  # Border size
			#" -z" + str (self.varDisplaySize.get()),  # Display size and bit depth
			" -a" + str (self.varAudioRate.get()),  # Audio sampling rate
			" -e " + config.systemrompath + config.ExecList [self.varExecIndex.get()] [1],  # Pointer to selected Executive ROM
			" -g " + config.systemrompath + config.GROMList [self.varGROMIndex.get()] [1],  # Pointer to selected Graphics ROM
			" -E " + config.systemrompath + config.ecsrom if self.varECS.get() else "",  # Pointer to ECS ROM image (if applicable)
			"\n"])
		file.write ("if [ -e \"" + basefilename + ".jpg\" ] ; then\n")  # If there was an overlay image, ...
		file.write ("\tpkill feh\n")  # Then get rid of the window.
		file.write ("fi\n")
		file.write ("if [ -e \"" + basefilename + ".pdf\" ] ; then\n")  # If there was an instruction manual, ...
		file.write ("\tpkill xpdf\n")  # Then get rid of the PDF window.
		file.write ("fi\n")
		file.write ("if [ -e \"" + basefilename + ".png\" ] ; then\n")  # If there was a box image, ...
		#file.write ("\tfeh --bg-max -z *.jpg \n")  # Then replace the "wallpaper" with something we were using before.
		file.write ("\tpkill feh\n")  # Then get rid of the window.
		file.write ("fi\n")
		file.write ("make " + sys.argv [1] + " &\n" if len (sys.argv) > 1 else "make &\n")  # Re-launch this application.
		file.close()
		self.quit()

	# This code fires when the About button is checked.
	def doabout (self):
		tk.messagebox.showinfo ("About PIDEGS", "PIDEGS - Portable Intellivision Development Environment Graphical Suite\n\nWritten by Michael Hayes\n\nDate Of Last Modification:\nJuly 10, 2025")

	# This code fires when the Quit button is checked.
	def doquit (self):
		file.close()
		self.quit()

app = Application()
app.master.title ("Portable Intellivision Development Environment Graphical Suite")
app.master.geometry ("+0+0")
app.master.iconphoto (True, tk.PhotoImage (file = config.workingpath + "blueeye.png"))
app.configure (bg = config.colorpanelsbg)
file = open (config.workingpath + "temp.sh", "w")
file.write (config.hashbang + "\n")
file.write ("source " + config.workingpath + "includes.sh\n")  # Common functions in a separate file
app.mainloop()  # Listen for events.  Let the fun begin!
