Jump to content
  • Announcement

    The HyperSpin 2 beta is here!

    We’re starting the first public testing phase with Platinum Members to keep the scope manageable while we test the current feature set and begin to add more. In the future, we’ll provide a version for basic members as well.  On behalf of the entire HyperSpin team, we look forward to another exciting adventure with our community.

WinRar 5 vs 7zip : Fasten your seatbelts!


bb_neo

Recommended Posts

Posted

well that's just it, if I get the script to actually function independently then theorectally it should just paste into RL and add rar5 functionality ala hl2 style while all the fancy doodad awesome RL extras only work for 7z. It won't be as cool and take advantage of all your new hooks and work yet, but it takes the pressure off yet another feature request...

If its completely self contained, why wouldn't it work?

also to everyone I am no programmer I can just kinda figure out code sometimes when I look at it. I make no promises I am just hoping it works and am willing to share.

  • Replies 63
  • Created
  • Last Reply
Posted

ok so I have it extracting, I have it cleaning up, I have it pseudo functional and it differentiates between rars and 7z/zip etc for the different routines.

My problem right now is that for whatever reason it pulls some loops and weird destination extraction directories only for the rar routine.

My extract path is S:\working directory for both rar and 7z

If I run a test HL for icebreaker on 3do I get

S:\Working directory\HS\Icebreaker (USA)\HS\Icebreaker (USA)\Icebreaker (USA)\Icebreaker.cue

S:\Working directory\HS\Icebreaker (USA)\HS\Icebreaker (USA)\Icebreaker (USA)\Icebreaker.iso

S:\Working directory\HS\Icebreaker (USA)\Icebreaker (USA)\Icebreaker.cue

S:\Working directory\HS\Icebreaker (USA)\Icebreaker (USA)\Icebreaker.iso

double extracting to multiple folders nested in each other.

I don't quite understand why it's doing this.

This is where I am at right now

;-----------------------------------------------------------------------------------------------------------------------------------------
; HyperLaunch V2.25c
; By BBB & djvj
; This can only be compiled with Authotkey_H
; http://www.autohotkey.com/forum/topic43049.html
; Replace your normal autohotkey.exe with the one from autohotkey_h
; Requires autohotkey.dll
; Must reside in HS install directory
;
; Added unrar.exe support by tastyratz
;
;
;-----------------------------------------------------------------------------------------------------------------------------------------

#NoTrayIcon
#SingleInstance Ignore
#InstallKeybdHook
SetTitleMatchMode 2
DetectHiddenWindows, ON
SetWorkingDir % A_ScriptDir
logFile = %A_ScriptDir%\HyperLaunch.log
Version = 2.25d
forHS2 = false	; remove when HS2 released
#Include %A_ScriptDir%\Gdip.ahk
;-----------------------------------------------------------------------------------------------------------------------------------------
;-----------------------------------------------------------------------------------------------------------------------------------------
; Gui
;-----------------------------------------------------------------------------------------------------------------------------------------
;-----------------------------------------------------------------------------------------------------------------------------------------
;Read last system and last rom so we dont have to fill it in for testing
settingsFile := checkFile(A_ScriptDir . "\Settings\Settings.ini")
; globalFile := checkFile(A_ScriptDir . "\Settings\Global Settings.ini") ; UNCOMMENT WHEN HS2 COMES OUT
globalFile := A_ScriptDir . "\Settings\Global Settings.ini" ; REMOVE WHEN HS2 COMES OUT, not everyone will have this file yet
IfNotExist, %globalFile%
GoSub, CreateGlobalFile

lastSystem := IniReadCheck(settingsFile, "HyperLaunch", "Last_System")
lastRom := IniReadCheck(settingsFile, "HyperLaunch", "Last_Rom")

hideCursorGlobal := IniReadCheck(globalFile, "HyperLaunch", "Hide_Cursor", "false") ; hide cursor, only used for gui launching
If (hideCursorGlobal = "true"){
hideCursorChecked = 1
}Else{
hideCursorChecked = 0
}
hideDesktopGlobal := IniReadCheck(globalFile, "HyperLaunch", "Hide_Desktop", "false")
If (hideDesktopGlobal = "true"){
hideDesktopChecked = 1
}Else{
hideDesktopChecked = 0
}
hideTaskbarGlobal := IniReadCheck(globalFile, "HyperLaunch", "Hide_Taskbar", "false")
If (hideTaskbarGlobal = "true"){
hideTaskbarChecked = 1
}Else{
hideTaskbarChecked = 0
}   

;-----------------------------------------------------------------------------------------------------------------------------------------
; Starting Log
;-----------------------------------------------------------------------------------------------------------------------------------------
FileDelete, %logFile%
Log("[code]","start")
Log("HyperLaunch v" . Version)
WinGetPos,,, hsW, hsH, HyperSpin,, Notepad
isAdmin:=(If A_IsAdmin=1 ? ("Yes") : ("No"))
logTxt := "System Specs:`n`t`tHyperSpin Dir: " . A_ScriptDir . "`n`t`tOS: " . A_OSVersion . "`n`t`tOS Language: " . A_Language . "`n`t`tOS Admin Status: " . isAdmin:=(If A_IsAdmin=1 ? ("Yes") : ("No"))
SysGet, MonitorCount, MonitorCount, SysGet, MonitorPrimary, MonitorPrimary
Loop, %MonitorCount% ; get each monitor's stats for the log
{
SysGet, MonitorName, MonitorName, %A_Index%
SysGet, Monitor, Monitor, %A_Index%
SysGet, MonitorWorkArea, MonitorWorkArea, %A_Index%
logTxt .= "`n`t`tMonitor #" . A_Index . (If MonitorPrimary = A_Index ? (" (Primary)"):("")) . " (" . MonitorName . "): " . MonitorRight . "x" . MonitorBottom . " (" . MonitorWorkAreaRight . "x" . MonitorWorkAreaBottom . " work)"
}
logTxt .= "`n`t`tHyperSpin Res: " . hsW . "x" . hsH . "`n`t`tAHK Version: " . A_AhkVersion
Log(logTxt)
; HyperSpin_2_0
; ahk_class ApolloRuntimeContentWindow
; HyperSpin
; ahk_class ThunderRT6FormDC

If 0 < 2
{
;Read system xml to optionally fill in the first combo
Hotkey, ~Enter, Button1
getSystems()
Gui, Add, Text, x12 y10 w430 h20 , Command Line: HyperLaunch.exe SystemName RomName
Gui, Add, Text, x12 y40 w360 h30 , You can run a test below by entering the system name and rom name below then clicking the Test button.
Gui, Add, Edit, x12 y150 w266 h20 vEdit2, %lastRom%
Gui, Add, Text, x12 y80 w80 h20 , System Name:
Gui, Add, Text, x12 y130 w140 h20 , Rom Name(no extension):
Gui, Add, Button, x312 y100 w60 h70 gButton1, Test
Gui, Add, Button, x262 y180 w110 h40 gButton2, Download Modules
Gui, Add, Button, x279 y150 w24 h20 gButton3, .
Gui, Add, Button, x279 y100 w24 h20 gButton4, .
Gui, Add, Checkbox, x12 y180 w130 h20 vCheck1, Debug Module Script
Gui, Add, CheckBox, x12 y200 w130 h20 Checked%hideCursorChecked% vChecked2 gCheck2, Hide Cursor
Gui, Add, CheckBox, x142 y180 w110 h20 Checked%hideDesktopChecked% vChecked3 gCheck3, Hide Desktop
Gui, Add, CheckBox, x142 y200 w110 h20 Checked%hideTaskbarChecked% vChecked4 gCheck4, Hide Taskbar
Gui, Show, Center h233 w386, HyperLaunch %Version%

Log("HyperLaunch launched directly")
Return
}Else{
systemName = %1%
romName = %2%
; Blocking enter to avoid duplicate HyperLaunch launches
; Hotkey, Enter, BlockKeyInput
; Hotkey, 1, BlockKeyInput
Goto, Start
Return
}

Check2:
Gui, Submit , NoHide
If (Checked2 = 0){
	IniWrite, false, %globalFile%, HyperLaunch, Hide_Cursor
}Else{
	IniWrite, true, %globalFile%, HyperLaunch, Hide_Cursor
}
IniRead, hideCursor, %globalFile%, HyperLaunch, Hide_Cursor, false
Return

Check3:
Gui, Submit , NoHide
If (Checked3 = 0){
	IniWrite, false, %globalFile%, HyperLaunch, Hide_Desktop
}Else{
	IniWrite, true, %globalFile%, HyperLaunch, Hide_Desktop
}  
IniRead, hideDesktop, %globalFile%, HyperLaunch, Hide_Desktop, false 
Return

Check4:
Gui, Submit , NoHide
If (Checked4 = 0){
	IniWrite, false, %globalFile%, HyperLaunch, Hide_Taskbar
}Else{
	IniWrite, true, %globalFile%, HyperLaunch, Hide_Taskbar
}  
IniRead, hideTaskbar, %globalFile%, HyperLaunch, Hide_Taskbar, false
Return

Button3:
;File browser
;Try and get the users rompath to start in
Gui, Submit, NoHide
If forHS2 = true
	IniRead, startDir, %A_ScriptDir%\Settings\%Edit1%.ini, Exe Info, Rom_Path, %A_ScriptDir%
Else
	IniRead, startDir, %A_ScriptDir%\Settings\%Edit1%.ini, Exe Info, Rompath, %A_ScriptDir%
startDir := GetFullName(startDir)
StringRight, lastChar, startDir, 1
If (lastChar = "\"){
	StringTrimRight, startDir, startDir, 1 
}
FileSelectFile, SelectedFile, 3, %startDir%, Select a rom,
If SelectedFile =
	Return
Else
	RegExMatch(SelectedFile,  "\\([^\\]*)\.\w{2,3}$", SubPat) 
GuiControl,, Edit2, %SubPat1%
Return

Button4:
;Opens new gui to configure an emu
Gui, Submit , NoHide 
Gui, 3:+owner1
Gui +Disabled
configFile := checkFile(A_ScriptDir . "\Settings\" . Edit1 . ".ini")
IniRead, configExePath, %configFile%, Exe Info, Path,
StringRight, lastChar, configExePath, 1
If (lastChar != "\"){
	configExePath += "\"
}

IniRead, configExe, %configFile%, Exe Info, Exe
If forHS2 = true
	IniRead, configRomPath, %configFile%, Exe Info, Rom_Path
Else
	IniRead, configRomPath, %configFile%, Exe Info, Rompath
IniRead, configRomExtension, %configFile%, Exe Info, Romextension
configPerGameModules := IniReadCheck(configFile, "Exe Info", "Per_Game_Modules", "false")
configCPWizardEnabled := IniReadCheck(configFile, "Exe Info", "Cp_Wizard_Enabled", "use_global")

finalPath = %configExePath%%configExe%
If (finalPath = 0){
	finalPath := ""
}

Gui, 3:Add, Text, x12 y10 w210 h20 , Emulator:
Gui, 3:Add, Text, x12 y60 w210 h20 , Rom Path:
Gui, 3:Add, Text, x12 y110 w210 h20 , Rom Extension:
Gui, 3:Add, Edit, x12 y30 w330 h20 v3Edit1 g3Edit1, %finalPath%
Gui, 3:Add, Edit, x12 y80 w330 h20 v3Edit2 g3Edit2, %configRomPath%
Gui, 3:Add, Edit, x12 y130 w330 h20 v3Edit3 g3Edit3, %configRomExtension% 
Gui, 3:Add, Button, x342 y30 w20 h20 g3Button1, .
Gui, 3:Add, Button, x342 y80 w20 h20 g3Button2, .

If (configPerGameModules = "true"){
	configPerGameModulesChecked = 1
}Else{
	configPerGameModulesChecked = 0
} 

If (configCPWizardEnabled = "true"){
	configCPWizardEnabledChecked = 1
}Else{
	configCPWizardEnabledChecked = 0
}  

Gui, 3:Add, CheckBox, x12 y160 w120 h20 Checked%configPerGameModulesChecked% v3Checked1 g3Check1, Per Game Modules
Gui, 3:Add, CheckBox, x142 y160 w100 h20 Checked%configCPWizardEnabledChecked% v3Checked2 g3Check2, Enable CPWizard
Gui, 3:Show, x550 y301 h211 w372, Quick Config
Return

3GuiClose:
Gui, 1:-Disabled
Gui, 3:Destroy
Return

3Edit1:
Gui, 3:Submit, NoHide
RegExMatch(3Edit1,  "(.*\\)([^\\]*\.\w{2,3})$", SubPat)
IniWrite, %SubPat1%, %configFile%, Exe Info, Path
IniWrite, %SubPat2%, %configFile%, Exe Info, Exe
Return

3Edit2:
Gui, 3:Submit, NoHide
If forHS2 = true
	IniWrite, %3Edit2%, %configFile%, Exe Info, Rom_Path
Else
	IniWrite, %3Edit2%, %configFile%, Exe Info, Rompath
Return

3Edit3:
Gui, 3:Submit , NoHide
IniWrite, %3Edit3%, %configFile%, Exe Info, Romextension
Return

3Check1:
Gui, 3:Submit , NoHide
If (3Checked1 = 0){
	IniWrite, false, %configFile%, Exe Info, Per_Game_Modules
}Else{
	IniWrite, true, %configFile%, Exe Info, Per_Game_Modules
}
Return

3Check2:
Gui, 3:Submit , NoHide
If (3Checked2 = 0){
	IniWrite, false, %configFile%, Exe Info, Cp_Wizard_Enabled
}Else{
	IniWrite, true, %configFile%, Exe Info, Cp_Wizard_Enabled
}
Return

Button2:
Run, http://hyperlist.hyperspin-fe.com/?module=browseahk
Return

Button1:
IfWinActive, HyperLaunch
{
	Gui, Submit , NoHide
	Hotkey, ~Enter, Off
	systemName = %Edit1%																													  
	romName = %Edit2%
	debugModule = %Check1%
	Goto, Start
}
Return

3Button1:
Gui, 3:Submit, NoHide
FileSelectFile, SelectedFile, 3, %3Edit1%, Select Executable,
If SelectedFile =
	Return
Else
	RegExMatch(SelectedFile,  "(.*\\)([^\\]*\.\w{3,3})$", SubPat)
IniWrite, %SubPat1%, %configFile%, Exe Info, Path
IniWrite, %SubPat2%, %configFile%, Exe Info, Exe
GuiControl,, 3Edit1, %SubPat1%%SubPat2%
Return

3Button2:
Gui, 3:Submit, NoHide
StringRight, lastChar, 3Edit2, 1
If (lastChar = "\"){
	StringTrimRight, startDir, 3Edit2, 1
}
FileSelectFolder, selectedFolder, *%startDir%, Select RomPath,
If selectedFolder =
	Return
Else
	StringRight, lastChar, selectedFolder, 1
If (lastChar != "\"){
	selectedFolder = %selectedFolder%\
}

If forHS2 = true
	IniWrite, %selectedFolder%, %configFile%, Exe Info, Rom_Path
Else
	IniWrite, %selectedFolder%, %configFile%, Exe Info, Rompath
GuiControl,, 3Edit2, %selectedFolder%
Return

BlockKeyInput:
Sleep, 2500
Hotkey, Enter, off
Hotkey, 1, off
Return

Start:
Gui Destroy
IniWrite, %systemName%, %settingsFile%, HyperLaunch, Last_System
IniWrite, %romName%, %settingsFile%, HyperLaunch, Last_Rom

Log("HyperLaunch received """ . systemName . """ and """ . romName . """")

;-----------------------------------------------------------------------------------------------------------------------------------------
;-----------------------------------------------------------------------------------------------------------------------------------------
; Get Ini Settings
;-----------------------------------------------------------------------------------------------------------------------------------------
;-----------------------------------------------------------------------------------------------------------------------------------------
; In HS2, if using PCLauncher, your systemName will be PCLauncher, instead of your wheel's name
If (systemName = "Main Menu")
iniName = %romName%
Else ;If (systemName != "PCLauncher") ; Probably don't want this "If" check anymore because PCLauncher needs an ini so it can check for fade functionality
iniName = %systemName%


; If (systemName != "PCLauncher") ; Same as above comment, need to check for an ini from now on
iniFile := checkFile(A_ScriptDir . "\Settings\" . iniName . ".ini")

;-----------------------------------------------------------------------------------------------------------------------------------------
; Main Settings from Settings\Settings.ini
;-----------------------------------------------------------------------------------------------------------------------------------------
exitScriptKey := IniReadCheck(settingsFile, "HyperLaunch", "Exit_Script_Key", "~q & ~s")
exitEmulatorKey := IniReadCheck(settingsFile, "HyperLaunch", "Exit_Emulator_Key", "Esc")
toggleCursorKey := IniReadCheck(settingsFile, "HyperLaunch", "Toggle_Cursor_Key", "t")
mgKey := IniReadCheck(settingsFile, "HyperLaunch", "MultiGame_Key", "NumpadSub")
mgSelectKey := IniReadCheck(settingsFile, "HyperLaunch", "MultiGame_Select_Key", "Enter")
mgExitKey := IniReadCheck(settingsFile, "HyperLaunch", "MultiGame_Exit_Key", "Esc")
daemonToolsPath := IniReadCheck(settingsFile, "HyperLaunch", "Path_To_Daemontools")
daemonToolsPath := GetFullName(daemonToolsPath)
cpWizardPath := IniReadCheck(settingsFile, "HyperLaunch", "Path_To_CPWizard")
cpWizardPath := GetFullName(cpWizardPath)

fadeInInterruptKeys := IniReadCheck(settingsFile, "HyperLaunch", "Fade_In_Interrupt_Keys", "anykey")

keymapperFullPath := IniReadCheck(settingsFile, "HyperLaunch", "Keymapper_Path", A_Space)
keymapperProfilePath := IniReadCheck(settingsFile, "HyperLaunch", "Keymapper_Profiles_Path", A_ScriptDir . "\Keymapper Profiles\")
IfInString, keymapperProfilePath, `%A_ScriptDir`% ; replacing default value if it exists with user's actual HS path
{
StringReplace, keymapperProfilePath, keymapperProfilePath, `%A_ScriptDir`%, %A_ScriptDir%
IniWrite, %keymapperProfilePath%, %settingsFile%, HyperLaunch, Keymapper_Profiles_Path
}

;-----------------------------------------------------------------------------------------------------------------------------------------
; Global Settings from Settings\Global Settings.ini
;-----------------------------------------------------------------------------------------------------------------------------------------
cpWizardEnabledGlobal := IniReadCheck(globalFile, "HyperLaunch", "CPWizard_Enabled", "false")
cpWizardDelayGlobal := IniReadCheck(globalFile, "HyperLaunch", "CPWizard_Delay", 8000)
cpWizardParamsGlobal := IniReadCheck(globalFile, "HyperLaunch", "CPWizard_Params", "-minimized -timeout 9000")

fadeInGlobal := IniReadCheck(globalFile, "HyperLaunch", "Fade_In", "false")
fadeOutGlobal := IniReadCheck(globalFile, "HyperLaunch", "Fade_Out", "false")
fadeColorGlobal := IniReadCheck(globalFile, "HyperLaunch", "Fade_Color", "0x000000")
fadeInDurationGlobal := IniReadCheck(globalFile, "HyperLaunch", "Fade_In_Duration", "500")
fadeOutDurationGlobal := IniReadCheck(globalFile, "HyperLaunch", "Fade_Out_Duration", "500")
fadeInDelayGlobal := IniReadCheck(globalFile, "HyperLaunch", "Fade_In_Delay", "0")

7zEnableGlobal := IniReadCheck(globalFile, "HyperLaunch", "7z_Enabled", "false")
7zExtractDirFromIniGlobal := IniReadCheck(globalFile, "HyperLaunch", "7z_Extract_Dir", A_Temp . "\Hyperspin\")
7zDelTempGlobal := IniReadCheck(globalFile, "HyperLaunch", "7z_Delete_Temp", "true")

;Added by Tastyratz for Winrar support +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+----------
rarEnableGlobal := IniReadCheck(globalFile, "HyperLaunch", "rar_Enabled", "false")
rarExtractDirFromIniGlobal := IniReadCheck(globalFile, "HyperLaunch", "rar_Extract_Dir", A_Temp . "\Hyperspin\")
rarDelTempGlobal := IniReadCheck(globalFile, "HyperLaunch", "rar_Delete_Temp", "true")


keymapperEnabledGlobal := IniReadCheck(globalFile, "HyperLaunch", "Keymapper_Enabled", "false")
keymapperGlobal := IniReadCheck(globalFile, "HyperLaunch", "Keymapper", A_Space)

mgEnabledGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Enabled", "false")
mgBackgroundColorGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Background_Color", "FF000000")
mgSidePaddingGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Side_Padding", "0.2")
mgYOffsetGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Y_Offset", "500")
mgImageAdjustGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Image_Adjust", "1")
mgFontGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Font", "Arial")
mgText1OptionsGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Text_1_Options", "x10p y30p w80p Centre cBBFFFFFF r4 s100 Bold Italic")
mgText1TextGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Text_1_Text", "Please select a game")
mgText2OptionsGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Text_2_Options", "w96p cFFFFFFFF r4 s50 Center Bold Italic")
mgText2OffsetGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Text_2_Offset", "70")
mgUseSoundGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Use_Sound", "true")
mgSoundfreqGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Sound_Frequency", "300")
mgExitEffectGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Exit_Effect", "none")
mgSelectedEffectGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Selected_Effect", "rotate")
mgUseGameArtGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Use_Game_Art", "false")
mgArtworkDirGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Art_Folder", "Artwork1")

;-----------------------------------------------------------------------------------------------------------------------------------------
; System Specific Settings from systemName.ini
;-----------------------------------------------------------------------------------------------------------------------------------------
IniRead, emuPath, %iniFile%, Exe Info, Path
emuPath := GetFullName(emuPath)
If forHS2 = true
IniRead, romPathFromIni, %iniFile%, Exe Info, Rom_Path
Else
IniRead, romPathFromIni, %iniFile%, Exe Info, Rompath
romPath := GetFullName(romPathFromIni)
IniRead, executable, %iniFile%, Exe Info, Exe
IniRead, romExtensions, %iniFile%, Exe Info, Romextension

perGameModules := IniReadCheck(iniFile, "Exe Info", "Per_Game_Modules", "false")
skipChecks := IniReadCheck(iniFile, "Exe Info", "Skipchecks", "false")

hideCursorSystem := IniReadCheck(iniFile, "Exe Info", "Hide_Cursor", "use_global")
hideDesktopSystem := IniReadCheck(iniFile, "Exe Info", "Hide_Desktop", "use_global")
hideTaskbarSystem := IniReadCheck(iniFile, "Exe Info", "Hide_Taskbar", "use_global")

cpWizardEnabledSystem := IniReadCheck(iniFile, "Exe Info", "CPWizard_Enabled", "use_global")
cpWizardDelaySystem := IniReadCheck(iniFile, "Exe Info", "CPWizard_Delay", "use_global")
cpWizardParamsSystem := IniReadCheck(iniFile, "Exe Info", "CPWizard_Params", "use_global")

fadeInSystem := IniReadCheck(iniFile, "Exe Info", "Fade_In", "use_global")
fadeOutSystem := IniReadCheck(iniFile, "Exe Info", "Fade_Out", "use_global")
fadeColorSystem := IniReadCheck(iniFile, "Exe Info", "Fade_Color", "use_global")
fadeInDurationSystem := IniReadCheck(iniFile, "Exe Info", "Fade_In_Duration", "use_global")
fadeOutDurationSystem := IniReadCheck(iniFile, "Exe Info", "Fade_Out_Duration", "use_global")
fadeInDelaySystem := IniReadCheck(iniFile, "Exe Info", "Fade_In_Delay", "use_global")

7zEnableSystem := IniReadCheck(iniFile, "Exe Info", "7z_Enabled", "use_global")
7zExtractDirFromIniSystem := IniReadCheck(iniFile, "Exe Info", "7z_Extract_Dir", "use_global")
7zDelTempSystem := IniReadCheck(iniFile, "Exe Info", "7z_Delete_Temp", "use_global")

;Added by Tastyratz for Winrar support +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+----------
rarEnableSystem := IniReadCheck(iniFile, "Exe Info", "rar_Enabled", "use_global")
rarExtractDirFromIniSystem := IniReadCheck(iniFile, "Exe Info", "rar_Extract_Dir", "use_global")
rarDelTempSystem := IniReadCheck(iniFile, "Exe Info", "rar_Delete_Temp", "use_global")

keymapperEnabledSystem := IniReadCheck(iniFile, "Exe Info", "Keymapper_Enabled", "use_global") ; per system enable key
keymapperSystem := IniReadCheck(iniFile, "Exe Info", "Keymapper", "use_global") ; per system keymapper

mgEnabledSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Enabled", "use_global")
mgBackgroundColorSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Background_Color", "use_global")
mgSidePaddingSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Side_Padding", "use_global")
mgYOffsetSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Y_Offset", "use_global")
mgImageAdjustSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Image_Adjust", "use_global")
mgFontSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Font", "use_global")
mgText1OptionsSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Text_1_Options", "use_global")
mgText1TextSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Text_1_Text", "use_global")
mgText2OptionsSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Text_2_Options", "use_global")
mgText2OffsetSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Text_2_Offset", "use_global")
mgUseSoundSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Use_Sound", "use_global")
mgSoundfreqSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Sound_Frequency", "use_global")
mgExitEffectSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Exit_Effect", "use_global")
mgSelectedEffectSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Selected_Effect", "use_global")
mgUseGameArtSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Use_Game_Art", "use_global")
mgArtworkDirSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Art_Folder", "use_global")

;-----------------------------------------------------------------------------------------------------------------------------------------
; Converting Global/System variables for use later
;-----------------------------------------------------------------------------------------------------------------------------------------
hideCursor := (If hideCursorSystem = "use_global" ? (hideCursorGlobal) : (hideCursorSystem))
hideDesktop := (If hideDesktopSystem = "use_global" ? (hideDesktopGlobal) : (hideDesktopSystem))
hideTaskbar := (If hideTaskbarSystem = "use_global" ? (hideTaskbarGlobal) : (hideTaskbarSystem))

cpWizardEnabled := (If cpWizardEnabledSystem= "use_global" ? (cpWizardEnabledGlobal) : (cpWizardEnabledSystem))
cpWizardDelay := (If cpWizardDelaySystem= "use_global" ? (cpWizardParamsGlobal) : (cpWizardDelaySystem))
cpWizardParams := (If cpWizardParamsSystem= "use_global" ? (cpWizardParamsGlobal) : (cpWizardParamsSystem))

keymapperEnabled := (If keymapperEnabledSystem= "use_global" ? (keymapperEnabledGlobal) : (keymapperEnabledSystem))
keymapper := (If keymapperSystem = "use_global" ? (keymapperGlobal) : (keymapperSystem))

fadeIn := (If fadeInSystem = "use_global" ? (fadeInGlobal) : (fadeInSystem))
fadeInDuration := (If fadeInDurationSystem = "use_global" ? (fadeInDurationGlobal) : (fadeInDurationSystem))
fadeInDelay := (If fadeInDelaySystem = "use_global" ? (fadeInDelayGlobal) : (fadeInDelaySystem))
fadeColor := (If fadeColorSystem = "use_global" ? (fadeColorGlobal) : (fadeColorSystem))
fadeOut := (If fadeOutSystem = "use_global" ? (fadeOutGlobal) : (fadeOutSystem))
fadeOutDuration := (If fadeOutDurationSystem = "use_global" ? (fadeOutDurationGlobal) : (fadeOutDurationSystem))

7zEnable := (If (7zEnableSystem = "use_global") ? (7zEnableGlobal) : (7zEnableSystem))
7zExtractDirFromIni := (If (7zExtractDirFromIniSystem = "use_global") ? (7zExtractDirFromIniGlobal) : (7zExtractDirFromIniSystem))
7zDelTemp := (If (7zDelTempSystem = "use_global") ? (7zDelTempGlobal) : (7zDelTempSystem))
7zExtractDir := 7zExtractDirFromIni

;Added by Tastyratz for Winrar support +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+----------
rarEnable := (If (rarEnableSystem = "use_global") ? (rarEnableGlobal) : (rarEnableSystem))
rarExtractDirFromIni := (If (rarExtractDirFromIniSystem = "use_global") ? (rarExtractDirFromIniGlobal) : (rarExtractDirFromIniSystem))
DelTemp := (If (rarDelTempSystem = "use_global") ? (rarDelTempGlobal) : (rarDelTempSystem))
rarExtractDir := rarExtractDirFromIni



mgEnabled := (If (mgEnabledSystem = "use_global") ? (mgEnabledGlobal) : (mgEnabledSystem))
mgBackgroundColor := (If (mgBackgroundColorSystem = "use_global") ? (mgBackgroundColorGlobal) : (mgBackgroundColorSystem))
mgSidePadding := (If (mgSidePaddingSystem = "use_global") ? (mgSidePaddingGlobal) : (mgSidePaddingSystem))
mgYOffset := (If (mgYOffsetSystem = "use_global") ? (mgYOffsetGlobal) : (mgYOffsetSystem))
mgImageAdjust := (If (mgImageAdjustSystem = "use_global") ? (mgImageAdjustGlobal) : (mgImageAdjustSystem))
mgFont := (If (mgFontSystem = "use_global") ? (mgFontGlobal) : (mgFontSystem))
mgText1Options := (If (mgText1OptionsSystem = "use_global") ? (mgText1OptionsGlobal) : (mgText1OptionsSystem))
mgText1Text := (If (mgText1TextSystem = "use_global") ? (mgText1TextGlobal) : (mgText1TextSystem))
mgText2Options := (If (mgText2OptionsSystem = "use_global") ? (mgText2OptionsGlobal) : (mgText2OptionsSystem))
mgText2Offset := (If (mgText2OffsetSystem = "use_global") ? (mgText2OffsetGlobal) : (mgText2OffsetSystem))
mgUseSound := (If (mgUseSoundSystem = "use_global") ? (mgUseSoundGlobal) : (mgUseSoundSystem))
mgSoundfreq := (If (mgSoundfreqSystem = "use_global") ? (mgSoundfreqGlobal) : (mgSoundfreqSystem))
mgExitEffect := (If (mgExitEffectSystem = "use_global") ? (mgExitEffectGlobal) : (mgExitEffectSystem))
mgSelectedEffect := (If (mgSelectedEffectSystem = "use_global") ? (mgSelectedEffectGlobal) : (mgSelectedEffectSystem))
mgUseGameArt := (If (mgUseGameArtSystem = "use_global") ? (mgUseGameArtGlobal) : (mgUseGameArtSystem))
mgArtworkDir := (If (mgArtworkDirSystem = "use_global") ? (mgArtworkDirGlobal) : (mgArtworkDirSystem))

; msgbox, iniFile=%iniFile%`nsettingsFile=%settingsFile%`nglobalFile=%globalFile%`n`nSettings.ini`n`nexitScriptKey=%exitScriptKey%`nexitEmulatorKey=%exitEmulatorKey%`ntoggleCursorKey=%toggleCursorKey%`ndaemonToolsPath=%daemonToolsPath%`ncpWizardPath=%cpWizardPath%`ncpWizardDelay=%cpWizardDelay%`ncpWizardParams=%cpWizardParams%`nfadeInInterruptKeys=%fadeInInterruptKeys%`nkeymapperFullPath=%keymapperFullPath%`nkeymapperProfilePath=%keymapperProfilePath%`n`nGlobal Settings.ini`n`nfadeInGlobal=%fadeInGlobal%`nfadeOutGlobal=%fadeOutGlobal%`nfadeColorGlobal=%fadeColorGlobal%`nfadeInDurationGlobal=%fadeInDurationGlobal%`nfadeOutDurationGlobal=%fadeOutDurationGlobal%`nfadeInDelayGlobal=%fadeInDelayGlobal%`nkeymapperEnabledGlobal=%keymapperEnabledGlobal%`nkeymapperGlobal=%keymapperGlobal%`nmgBackgroundColorGlobal=%mgBackgroundColorGlobal%`nmgYOffsetGlobal=%mgYOffsetGlobal%`nmgImageAdjustGlobal=%mgImageAdjustGlobal%`nmgFontGlobal=%mgFontGlobal%`nmgText1OptionsGlobal=%mgText1OptionsGlobal%`nmgText1TextGlobal=%mgText1TextGlobal%`nmgText2OptionsGlobal=%mgText2OptionsGlobal%`nmgText2OffsetGlobal=%mgText2OffsetGlobal%`nmgUseSoundGlobal=%mgUseSoundGlobal%`nmgSoundfreqGlobal=%mgSoundfreqGlobal%`nmgExitEffectGlobal=%mgExitEffectGlobal%`n`n%systemName%.ini`n`nemuPath=%emuPath%`nromPath=%romPath%`nexecutable=%executable%`nromExtensions=%romExtensions%`nskipchecks=%skipchecks%`nperGameModules=%perGameModules%`ncpWizardEnabled=%cpWizardEnabled%`nfadeInSystem=%fadeInSystem%`nfadeOutSystem=%fadeOutSystem%`nfadeColorSystem=%fadeColorSystem%`nfadeInDurationSystem=%fadeInDurationSystem%`nfadeOutDurationSystem=%fadeOutDurationSystem%`nfadeInDelaySystem=%fadeInDelaySystem%`n7zEnable=%7zEnable%`n7zExtractDir=%7zExtractDir%`n7zDelTemp=%7zDelTemp%`nrarEnable=%rarEnable%`nrarExtractDir=%rarExtractDir%`nrarDelTemp=%rarDelTemp%`nkeymapperEnabledSystem=%keymapperEnabledSystem%`nkeymapperSystem=%keymapperSystem%`nmgEnabled=%mgEnabled%`nmgBackgroundColorSystem=%mgBackgroundColorSystem%`nmgYOffsetSystem=%mgYOffsetSystem%`nmgImageAdjustSystem=%mgImageAdjustSystem%`nmgFontSystem=%mgFontSystem%`nmgText1OptionsSystem=%mgText1OptionsSystem%`nmgText1TextSystem=%mgText1TextSystem%`nmgText2OptionsSystem=%mgText2OptionsSystem%`nmgText2OffsetSystem=%mgText2OffsetSystem%`nmgUseSoundSystem=%mgUseSoundSystem%`nmgSoundfreqSystem=%mgSoundfreqSystem%`nmgExitEffectSystem=%mgExitEffectSystem%

Log("INI Keys read")

;-----------------------------------------------------------------------------------------------------------------------------------------

; Check if emu is already running and/or cancel duplicate HyperLaunch launches. This is disabled for PCLauncher because %executable% is always blank, which causes ErrorLevel to not be 0.
If (systemName != "PCLauncher"){ ; This "If" is only for HS2, HS1 does not use PCLauncher as a systemName, so this "If" will always be true
Process, Exist, %executable%
If (ErrorLevel != 0) {
	Log("Possible duplicate launch. " . executable . " is already running, closing HyperLaunch")
	ExitApp
}
}

; Removes spaces from romExtensions if user accidentally placed them
StringReplace, romExtensions, romExtensions, %A_Space%,, All

;Verify settings
If (systemName != "PCLauncher" && skipChecks != "true"){
romExtension := checkPaths()
} Else If (skipChecks = "true") {
Log("skipChecks is enabled")
romExtension := GetExtensions() ; This is so we can still get our romExtension if we have skipchecks set to true for systems like scummvm and dosbox that do not contain a romName inside an archive
}
romExtensionOrig := romExtension ; Storing original romExtension in case 7z support is used, we lose original extension of the rom after processing through the 7z function. This is used when 7z and MultiGame support are used together.

; Convert fadeInInterruptKeys variable to cover all keys if user has it set for anykey
If (fadeInInterruptKeys = "anykey")
fadeInInterruptKeys = {LControl}{RControl}{LAlt}{RAlt}{LShift}{RShift}{LWin}{RWin}{AppsKey}{F1}{F2}{F3}{F4}{F5}{F6}{F7}{F8}{F9}{F10}{F11}{F12}{Left}{Right}{Up}{Down}{Home}{End}{PgUp}{PgDn}{Del}{Ins}{BS}{Capslock}{Numlock}{PrintScreen}{Pause}

;-----------------------------------------------------------------------------------------------------------------------------------------
; Build new script with module
; We'll use ahktextdll instead of ahkdll to add our own stuff to the script
; This will keep the modules more simplified
;-----------------------------------------------------------------------------------------------------------------------------------------
MScript := buildScript()
Log("Module is built")

;-----------------------------------------------------------------------------------------------------------------------------------------
; Load DLL
;-----------------------------------------------------------------------------------------------------------------------------------------
AhkDll := checkFile(A_ScriptDir . "\AutoHotkey.dll")
DllCall("LoadLibrary","Str",AhkDll)

;-----------------------------------------------------------------------------------------------------------------------------------------
;-----------------------------------------------------------------------------------------------------------------------------------------
; Pre Launch
;-----------------------------------------------------------------------------------------------------------------------------------------
;-----------------------------------------------------------------------------------------------------------------------------------------
HotKey, %exitScriptKey%, ExitScript

If (hideTaskbar = "true"){
Log("Hiding taskbar")
WinHide ahk_class Shell_TrayWnd
WinHide, ahk_class Button
}

If ( hideDesktop = "true" && fadeIn != "true" ){
;Were doing a dual hide really, one time for this thread and once for the module
;thread. But this is mainly for if the module writers forget to call it.
Log("Hiding desktop")
Gui, Color, 000000
Gui -Caption +ToolWindow ;+AlwaysOnTop
Gui, Show, x0 y0 W%A_ScreenWidth% H%A_ScreenHeight%, BlackScreen
}

If (hideCursor = "true"){
Log("Hiding mouse cursor")
Hotkey, %toggleCursorKey%, ToggleCursor
SystemCursor("Off")
;Also lets move it to the side since some emu's flash a cursor real quick
;even if we hide it.
CoordMode, Mouse
MouseMove, 0, 0, 0
}

If keymapperEnabled = true
{
	If keymapper not in xpadder,joytokey,ahk
		ScriptError("Your global keymapper is set to """ . keymapperGlobal . """ and this system is set to """ . keymapperSystem . """. Supported choices are xpadder`, joytokey`, or ahk and only one can be used per system",8)
	Log("Loading keymapper -> " . keymapper)
	If ( keymapper != "ahk" )
		CheckFile(keymapperFullPath) ; No need to continue if path set wrong
	SplitPath, keymapperFullPath, keymapperExe, keymapperPath, keymapperExt ; splitting pathname into variables
	hyperspinProfile = %keymapperProfilePath%HyperSpin ; profile while not in an emu and in HyperSpin
	defaultProfile = %keymapperProfilePath%default ; default profile for all systems, loaded when there is no system or rom specific profile
	systemProfile = %keymapperProfilePath%%systemName%\%systemName% ; profile for a specific system, loaded when no rom specific profile is found
	romProfile = %keymapperProfilePath%%systemName%\%romName% ; rom specific profile
	hyperspinProfile := LoadKeyMapper(MScript) ; returning profile in case user needs to load it on module exit
	; msgbox, keymapper variables`nkeymapperExe=%keymapperExe%`nkeymapperExt=%keymapperExt%`nkeymapperPath=%keymapperPath%
}

;-----------------------------------------------------------------------------------------------------------------------------------------
;-----------------------------------------------------------------------------------------------------------------------------------------
; Run Module To Start Launch
;-----------------------------------------------------------------------------------------------------------------------------------------
;-----------------------------------------------------------------------------------------------------------------------------------------

Log("Running module:`n" . MScript)
DllCall(AhkDll "\ahktextdll","Str",MScript,"Str",options,"Str",parameters,"Cdecl UInt")
If (ErrorLevel != 0)
ScriptError("Error running module.")

; The script waits here until the module is finished doing its thing.
While DllCall(AhkDll "\ahkReady")
Sleep, 100
; MsgBox Exiting Main Script

;-----------------------------------------------------------------------------------------------------------------------------------------
;-----------------------------------------------------------------------------------------------------------------------------------------
; Post Launch
;-----------------------------------------------------------------------------------------------------------------------------------------
;-----------------------------------------------------------------------------------------------------------------------------------------
Log("Module ended, exiting HyperLaunch normally")
ExitScript()

;-----------------------------------------------------------------------------------------------------------------------------------------
;-----------------------------------------------------------------------------------------------------------------------------------------
; Functions
;-----------------------------------------------------------------------------------------------------------------------------------------
;-----------------------------------------------------------------------------------------------------------------------------------------
buildScript(){
Static retStr
Static addHideDesktop
Static addFade
Static add7z
Static addrar

Global 0
Global 1
Global 2
Global debugModule
Global perGameModules
Global exitEmulatorKey
Global executable
Global romPath
Global romPathFromIni
Global emuPath
Global romExtension
Global romExtensionOrig
Global romExtensions
Global systemName
Global romName
Global daemonToolsPath
Global skipchecks
Global cpWizardEnabled
Global cpWizardPath
Global cpWizardDelay
Global cpWizardParams
Global hideDesktop
Global fadeIn
Global fadeOut
Global fadeColor
Global fadeInDuration
Global fadeOutDuration
Global fadeInDelay
Global fadeInInterruptKeys
Global 7zEnable
Global 7zExtractDir
Global 7zExtractDirOrig
Global 7zDelTemp
Global rarEnable
Global rarExtractDir
Global rarExtractDirOrig
Global rarDelTemp
Global mgEnabled
Global mgKey
Global mgSelectKey
Global mgExitKey
Global mgBackgroundColor
Global mgSidePadding
Global mgYOffset
Global mgImageAdjust
Global mgFont
Global mgText1Options
Global mgText1Text
Global mgText2Options
Global mgText2Offset
Global mgUseSound
Global mgSoundfreq
Global mgExitEffect
Global mgSelectedEffect
Global mgUseGameArt
Global mgArtworkDir

; Defining the file types we want to support throughout the script
; Some parts we need the period removed, so using 2 vars
7zFormats = .zip,.7z,.gzip,.tar
StringReplace, 7zFormatsNoP, 7zFormats,.,,All

;Added by Tastyratz for Winrar support +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+----------
; Defining the RAR file types we want to support throughout the script
; Some parts we need the period removed, so using 2 vars
rarFormats = .rar
StringReplace, rarFormatsNoP, rarFormats,.,,All

; Defining path for fadeIn Images
gameStartImgPath = %A_ScriptDir%\Media\%systemName%\Images\GameStart\
; Defining path for MultiGame Images
multiGameImgPath = %A_ScriptDir%\Media\%systemName%\Images\MultiGame\
; Defining path for the Module Extension folder
moduleExtensionPath = %A_ScriptDir%\Modules\Module Extensions\

If perGameModules = true
	moduleName := romName
Else
	moduleName := systemName

;Let's run through the module real quick and check for calls to any
;Global functions and add them in manually
moduleFile := checkFile(A_ScriptDir . "\Modules\" . moduleName . "\" . moduleName . ".ahk", "Cannot find: " . A_ScriptDir . "\Modules\" . moduleName . "\" . moduleName . ".ahk" . "`nYou do not have a HyperLaunch 2 module for " . moduleName . ". Please create one or check HyperList.")
Loop, read, %moduleFile%
{
	IfInString, A_LoopReadLine, hideDesktop()
		addHideDesktop := "true"
	IfInString, A_LoopReadLine, DaemonTools(
		addDaemonTools := "true"
}

;Common to all modules
retStr .= "`n;-----------------------------------------------------------"
retStr .= "`n;Built in script"
retStr .= "`n;-----------------------------------------------------------"
retStr .= "`n#NoTrayIcon"
retStr .= "`nDetectHiddenWindows, ON"
retStr .= "`nSetTitleMatchMode`, 2"
 ; required for ahk remapping to work properly with newer dll, might fix other bugs too:
retStr .= "`nSendMode`, Event"

;Common to all modules, inject vars into module
temp0 = %0% ; this is a quick fix for not being able to concenate number on the next line
retStr .= "`n0 = " . temp0
retStr .= "`nexitEmulatorKey = " . exitEmulatorKey
retStr .= "`nemuPath = " . emuPath
retStr .= "`nromPath = " . romPath
retStr .= "`nromPathFromIni = " . romPathFromIni
retStr .= "`nromExtension = " . romExtension
retStr .= "`nromExtensionOrig = " . romExtensionOrig
retStr .= "`nromExtensions = " . romExtensions
retStr .= "`nexecutable = " . executable
retStr .= "`nsystemName = " . systemName
retStr .= "`nromName = " . romName
retStr .= "`ndaemonToolsPath = " . daemonToolsPath
retStr .= "`nskipchecks = " . skipchecks
retStr .= "`nfadeIn = " . fadeIn
retStr .= "`nfadeOut = " . fadeOut
retStr .= "`nfadeColor = " . fadeColor
retStr .= "`nfadeInDuration = " . fadeInDuration
retStr .= "`nfadeOutDuration = " . fadeOutDuration
retStr .= "`nfadeInDelay = " . fadeInDelay
retStr .= "`nfadeInInterruptKeys = " . fadeInInterruptKeys
retStr .= "`ngameStartImgPath = " . gameStartImgPath
retStr .= "`nmoduleExtensionPath = " . moduleExtensionPath
retStr .= "`n7zEnable = " . 7zEnable
retStr .= "`n7zExtractDir = " . 7zExtractDir
retStr .= "`n7zExtractDirOrig = " . 7zExtractDirOrig
retStr .= "`n7zDelTemp = " . 7zDelTemp
retStr .= "`n7zFormats = " . 7zFormats
retStr .= "`n7zFormatsNoP = " . 7zFormatsNoP

;Added by Tastyratz for Winrar support +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+----------
retStr .= "`nrarEnable = " . rarEnable
retStr .= "`nrarExtractDir = " . rarExtractDir
retStr .= "`nrarDelTemp = " . rarDelTemp
retStr .= "`nrarFormats = " . rarFormats
retStr .= "`nrarFormatsNoP = " . rarFormatsNoP

retStr .= "`nmgEnabled = " . mgEnabled
retStr .= "`nmgKey = " . mgKey
retStr .= "`nmgSelectKey = " . mgSelectKey
retStr .= "`nmgExitKey = " . mgExitKey
retStr .= "`nmultiGameImgPath = " . multiGameImgPath
retStr .= "`nmgBackgroundColor = " . mgBackgroundColor
retStr .= "`nmgSidePadding = " . mgSidePadding
retStr .= "`nmgYOffset = " . mgYOffset
retStr .= "`nmgImageAdjust = " . mgImageAdjust
retStr .= "`nmgFont = " . mgFont
retStr .= "`nmgText1Options = " . mgText1Options
retStr .= "`nmgText1Text = " . mgText1Text
retStr .= "`nmgText2Options = " . mgText2Options
retStr .= "`nmgText2Offset = " . mgText2Offset
retStr .= "`nmgUseSound = " . mgUseSound
retStr .= "`nmgSoundfreq = " . mgSoundfreq
retStr .= "`nmgExitEffect = " . mgExitEffect
retStr .= "`nmgSelectedEffect = " . mgSelectedEffect
retStr .= "`nmgUseGameArt = " . mgUseGameArt
retStr .= "`nmgArtworkDir = " . mgArtworkDir

If cpWizardEnabled = true
{
	If cpWizardPath != ""
	{
		checkFile(cpWizardPath)
		retStr .= "`ncpWizardPath = " . cpWizardPath
		retStr .= "`ncpWizardDelay = " . cpWizardDelay
		retStr .= "`ncpWizardParams = " . cpWizardParams
	}Else{
		MsgBox Missing CPWizard Path and CPWizard is enabled
		ExitScript()
	}
} 

;Common to all modules, sets the exit key
;But this means all scripts no matter what require a CloseProcess
;whether its used or not.
retStr .= "`nHotkey, " . exitEmulatorKey . ", CloseProcess"

retStr .= "`n;-----------------------------------------------------------"
retStr .= "`n;Module script"
retStr .= "`n;-----------------------------------------------------------"

;Run CPWizard
If cpWizardEnabled = true
{
	Log("Running CPWizard")
	; retStr .= "`nRun`, ""%cpWizardPath%"" -emu ""%systemName%"" -game ""%romName%"" ""%cpWizardParams%"""
	retStr .= "`nRun`, ""%cpWizardPath%"" -emu ""%systemName%"" -game ""%romName%"" %cpWizardParams%"
	retStr .= "`nSleep`, %cpWizardDelay%"
}

;Add MultiGame hotkey if needed by the system
If mgEnabled = true
{
	If !FileExist(moduleExtensionPath . "Gdip.ahk") {
		IfNotExist, % moduleExtensionPath
			FileCreateDir, % moduleExtensionPath ; Need to create the folder first otherwise urldownload will fail
		UrlDownloadToFile, http://www.autohotkey.net/~tic/Gdip.ahk, % moduleExtensionPath . "Gdip.ahk"
		If ErrorLevel
			ScriptError("Error downloading gdip.ahk to the """"modules\Module Extensions\"""" folder.`n Either donwload is unavailable or  admin privledges are needed to write to this folder.")
	}
	retStr .= "`n`n#Include`, *i %A_ScriptDir%\Modules\Module Extensions\Gdip.ahk`nSetBatchLines`, -1`nHotkey`, %mgKey%`, StartMulti"
}

;Now insert the module script 
;We have to add each line individually for this to work
Loop, Read, %moduleFile%
{
	retStr .= "`n" . A_LoopReadLine
}

;Add Global HideDesktop function to module if it is used
; If addHideDesktop = true && hideDesktop = true
	retStr .= "`n`nhideDesktop(){`nGui`, Color`, 000000 `nGui -Caption +ToolWindow `nGui`, Show`, x0 y0 W%A_ScreenWidth% H%A_ScreenHeight%`, BlackScreen`n}" ; +AlwaysOnTop
; Else{
	;Still have to add a blank function so no error occurs.
	;This allows users to turn off desktop hiding even if the module writers make a call for it.
	; retStr .= "`n`nhideDesktop(){`n}"
; }

;Add Daemon Tools function to module if it is used
If addDaemonTools = true
	retStr .= "`n`nDaemonTools(action`,type=""dt""`,drive=0`,addDrive=""true""`,file=""""){`nGlobal daemonToolsPath`nfile := (If file ? (""``, """""" . file . """""""") : (""""))`nIfNotExist % daemonToolsPath`nScriptError(""Could not find "" . daemonToolsPath . ""``nPlease fix the path_to_daemontools key in your Settings\Global Settings.ini to point to your DTLite installation.""`,8)`nIf action not in mount`,unmount`nScriptError(action . "" is an unsupported use of daemontools. Only mount and unmount actions are supported."")`nIf type not in dt`,scsi`nScriptError(type . "" is an unsupported use of daemontools. Only dt and scsi drives are supported."")`nIf drive not in 0`,1`,2`,3`,4`nScriptError(drive . "" is an invalid virtual device number. Only 0 through 4 are supported."")`nRunWait`, %daemonToolsPath% -get_count %type%`nIf (ErrorLevel = 0 && addDrive != ""false"")`nRunWait`, %daemonToolsPath% -add %type%`nElse If ErrorLevel = 0`nScriptError(""You are trying to mount to a "" . type . "" virtual drive`, yet one does not exist."")`nRunWait`, %daemonToolsPath% -%action% %type%``, %drive%%file%`n}`n"

;Add Global FadeIn functions to module if they are used
If fadeIn = true
{
	retStr .= "`n`nFadeInStart(){`nStatic topPicSize`nStatic middlePicSize`nStatic bottomPicSize`nGlobal systemName`nGlobal fadeIn`nGlobal fadeColor`nGlobal fadeInDuration`nGlobal fadeInDelay`nGlobal fadeInInterruptKeys`nGlobal gameStartImgPath`nGlobal romName`nIf ( fadeIn = ""true"" ) {`ntopPic = %gameStartImgPath%top.png`nIfExist`, %gameStartImgPath%%romName%.png`nmiddlePic = %gameStartImgPath%%romName%.png`nElse`nmiddlePic = %gameStartImgPath%middle.png`nbottomPic = %gameStartImgPath%bottom.png`nGui`, 99:add`, picture`, vtopPicSize`, %topPic%`nGui`, 99:add`, picture`, vmiddlePicSize`, %middlePic%`nGui`, 99:add`, picture`, vbottomPicSize`, %bottomPic%`nGuiControlGet`, topPicSize`, 99:Pos`nGuiControlGet`, middlePicSize`, 99:Pos`nGuiControlGet`, bottomPicSize`, 99:Pos`nGui`, 99:destroy`nGui +LastFound`nWinGet GUI_ID`, ID`nGui +AlwaysOnTop -Caption +ToolWindow`nGui`, Color`, %fadeColor%`ntopXPos := ( A_ScreenWidth / 2 ) - ( topPicSizeW / 2 )`ntopYPos := 25`nmiddleXPos := ( A_ScreenWidth / 2 ) - ( middlePicSizeW / 2 )`nmiddleYPos := ( A_ScreenHeight / 2 ) - ( middlePicSizeH / 2 )`nbottomXPos := ( A_ScreenWidth / 2 ) - ( bottomPicSizeW / 2 )`nbottomYPos := ( A_ScreenHeight - bottomPicSizeH - 25 )`nGui`, Add`, Picture`,x%topXPos% y%topYPos%`, %topPic%`nGui`, Add`, Picture`,x%middleXPos% y%middleYPos%`, %middlePic%`nGui`, Add`, Picture`,x%bottomXPos% y%bottomYPos%`, %bottomPic%`nGui Show`, x0 y0 h%A_ScreenHeight% w%A_ScreenWidth% Hide`nDllCall(""AnimateWindow""`,""UInt""`,GUI_ID`,""Int""`,fadeInDuration`,""UInt""`,""0xa0000"")`nIf A_OSVersion In WIN_7,WIN_VISTA,WIN_XP`n{`nSetFormat`, Float`, 6.3`nfadeInDelay := (fadeInDelay/1000)`nfadeInDelay := (If fadeInDelay < 1 ? (""1"") : (fadeInDelay))`nInput`, SingleKey`, L1 T%fadeInDelay%, %fadeInInterruptKeys%`n} Else`nSleep`, %fadeInDelay%`nReturn GUI_ID`n}`n}"
	retStr .= "`n`nFadeInExit(){`nGlobal fadeIn`nGlobal fadeInDuration`nGlobal GUI_ID`nIf ( fadeIn = ""true"" ) {`nDllCall(""AnimateWindow""`,UInt`,GUI_ID`,UInt`,fadeInDuration`,UInt`,0x90000)`nGui Destroy`n}`n}"
}Else{
	; Still have to add a blank function so no error occurs.
	retStr .= "`n`nFadeInStart(){`n}"
	retStr .= "`n`nFadeInExit(){`n}"
}


;Add Global FadeOut functions to module if they are used
If fadeOut = true
{
	retStr .= "`n`nFadeOutStart(){`nSuspend`, On`nGlobal fadeOut`nGlobal fadeColor`nGlobal fadeOutDuration`nIf ( fadeOut = ""true"" ) {`nGui +LastFound`nWinGet GUI_ID3`, ID`nGui +AlwaysOnTop -Caption +ToolWindow`nGui Color`, %fadeColor%`nGui Show`, x0 y0 h%A_ScreenHeight% w%A_ScreenWidth% Hide`nDllCall(""AnimateWindow""`,""UInt""`,GUI_ID3`,""Int""`,fadeOutDuration`,""UInt""`,""0xa0000"")`n}`nReturn GUI_ID3`n}"
	retStr .= "`n`nFadeOutExit(){`nGlobal fadeOut`nGlobal fadeOutDuration`nGlobal GUI_ID3`nIf ( fadeOut = ""true"" ) {`nDllCall(""AnimateWindow""`,UInt`,GUI_ID3`,UInt`,fadeOutDuration`,UInt`,0x90000)`n}`n}"
}Else{
	;Still have to add a blank function so no error occurs.
	retStr .= "`n`nFadeOutStart(){`nSuspend`, On`n}"
	retStr .= "`n`nFadeOutExit(){`n}"
}

;Add 7z related functions to module if it is used
;Extracting rom if emulator doesn't support the compressed file type
If 7zEnable = true
{

; old function, before byref retStr .= "`n`n7z(path`, name`, ext`, ByRef 7zExtractDir){`nGlobal 7zEnable`nGlobal 7zFormats`nGlobal 7zFormatsNoP`nGlobal romExtensions`nGlobal romExtension`nGlobal romPath`nGlobal skipchecks`nIf ( 7zEnable = ""true"" ) {`n If romExtension in %7zFormats%`n{`nCheckForRomExt()`n7zPath = %A_ScriptDir%\7z.exe`n7zList := StdoutToVar_CreateProcess(7zPath . "" l """""" . path . name . ext . """""""")`nLoop`, Parse`, romExtensions`, ``,`n{`nIf ( skipchecks != ""true"" ) {`nIf A_LoopField in %7zFormatsNoP%`nContinue`n}`n7zExtractDirCheck = %7zExtractDir%HS\%name%\`nIfExist`, %7zExtractDirCheck%%name%.%A_LoopField%`n{`nromExtension = .%A_LoopField%`nromFound = true`n7zExtractDir = %7zExtractDirCheck%`nBreak`n}`nromIn7z := (InStr(7zList`, name . ""."" . A_LoopField) ? (""true"") : (""false""))`nIf ( romIn7z = ""true"" || skipchecks = ""true"" ) {`n7zExtractDir = %7zExtractDirCheck%`nRunWait`, %7zPath% e ""%path%%name%%ext%"" -aoa -o ""%7zExtractDir%""`,`,Hide`nIf ( ErrorLevel != 0 ) {`nIf ( ErrorLevel = 1 ) {`nError = Non fatal error, file may be in use by another application`n} Else If ( ErrorLevel = 2 ) {`nError = Fatal Error`n} Else If ( ErrorLevel = 7 ) {`nError = Command line error`n} Else If ( ErrorLevel = 8 ) {`nError = Not enough memory for operation`n} Else If ( ErrorLevel = 255 ) {`nError = User stopped the process`n} Else {`nError = Unknown 7zip Error`n}`nMsgBox`, 48`, 7zip.exe Error`, %Error%`, 5`nExitApp`n}`nIf (FileExist(7zExtractDir . name . ""."" . A_LoopField) || skipchecks = ""true"") { `nromExtension = .%A_LoopField% `nromFound = true`nBreak`n} Else`nromFound = false`n}`n}`nIf ( romFound = ""false"" )`nScriptError(""No extracted files found in "" . 7zExtractDir . ""``nCheck if you are exceeding the 255 character limit."")`nromPath = %7zExtractDir%`n}`n}`n}"
;	retStr .= "`n`n7z(ByRef 7zP`, ByRef 7zN`, ByRef 7zE`, ByRef 7zExtractDir){`nGlobal 7zEnable`nGlobal 7zFormats`nGlobal 7zFormatsNoP`nGlobal romExtensions`nGlobal skipchecks`nIf ( 7zEnable = ""true"" ) {`nIf 7zE in %7zFormats%`n{`nCheckForRomExt()`n7zPath = %A_ScriptDir%\7z.exe`n7zList := StdoutToVar_CreateProcess(7zPath . "" l """""" . 7zP . 7zN . 7zE . """""""")`nLoop`, Parse`, romExtensions`, ``,`n{`nIf ( skipchecks != ""true"" ) {`nIf A_LoopField in %7zFormatsNoP%`nContinue`n}`n7zExtractDirCheck = %7zExtractDir%HS\%7zN%\`nIfExist`, %7zExtractDirCheck%%7zN%.%A_LoopField%`n{`n7zE = .%A_LoopField%`nromFound = true`n7zExtractDir = %7zExtractDirCheck%`nBreak`n}`nromIn7z := (InStr(7zList`, 7zN . ""."" . A_LoopField) ? (""true"") : (""false""))`nIf ( romIn7z = ""true"" || skipchecks = ""true"" ) {`n7zExtractDir = %7zExtractDirCheck%`nRunWait`, %7zPath% x ""%7zP%%7zN%%7zE%"" -aoa -o""%7zExtractDir%""`,`,Hide`nIf ( ErrorLevel != 0 ) {`nIf ( ErrorLevel = 1 ) {`nError = Non fatal error, file may be in use by another application`n} Else If ( ErrorLevel = 2 ) {`nError = Fatal Error`n} Else If ( ErrorLevel = 7 ) {`nError = Command line error`n} Else If ( ErrorLevel = 8 ) {`nError = Not enough memory for operation`n} Else If ( ErrorLevel = 255 ) {`nError = User stopped the process`n} Else {`nError = Unknown 7zip Error`n}`nMsgBox`, 48`, 7zip.exe Error`, %Error%`, 5`nExitApp`n}`nIf (FileExist(7zExtractDir . 7zN . ""."" . A_LoopField) || skipchecks = ""true"") {`n7zE = .%A_LoopField% `nromFound = true`nBreak`n} Else`nromFound = false`n}`n}`nIf ( romFound = ""false"" )`nScriptError(""No extracted files found in "" . 7zExtractDir . ""``nCheck if you are exceeding the 255 character limit."")`n7zP = %7zExtractDir%`n}`n}`n}"
;	retStr .= "`n`n7z(ByRef 7zP`, ByRef 7zN`, ByRef 7zE`, ByRef 7zExtractDir){`nGlobal 7zEnable`nGlobal 7zFormats`nGlobal 7zFormatsNoP`nGlobal romExtensions`nGlobal skipchecks`nIf ( 7zEnable = ""true"" ) {`nIf 7zE in %7zFormats%`n{`nCheckForRomExt()`n7zPath = %A_ScriptDir%\7z.exe`n7zList := StdoutToVar_CreateProcess(7zPath . "" l """""" . 7zP . 7zN . 7zE . """""""")`nLoop`, Parse`, romExtensions`, ``,`n{`nIf ( skipchecks != ""true"" ) {`nIf A_LoopField in %7zFormatsNoP%`nContinue`n}`n7zExtractDirCheck = %7zExtractDir%HS\%7zN%\`nIfExist`, %7zExtractDirCheck%%7zN%.%A_LoopField%`n{`n7zE = .%A_LoopField%`nromFound = true`n7zExtractDir = %7zExtractDirCheck%`nBreak`n}`nromIn7z := (InStr(7zList`, 7zN . ""."" . A_LoopField) ? (""true"") : (""false""))`nIf ( romIn7z = ""true"" || skipchecks = ""true"" ) {`n7zExtractDir = %7zExtractDirCheck%`nRunWait`, %7zPath% x ""%7zP%%7zN%%7zE%"" -aoa -o""%7zExtractDir%""`,`,Hide`nIf ( ErrorLevel != 0 ) {`nIf ( ErrorLevel = 1 )`nError = Non fatal error`, file may be in use by another application`nElse If ( ErrorLevel = 2 )`nError = Fatal Error`nElse If ( ErrorLevel = 7 )`nError = Command line error`nElse If ( ErrorLevel = 8 )`nError = Not enough memory for operation`nElse If ( ErrorLevel = 255 )`nError = User stopped the process`nElse`nError = Unknown 7zip Error`nMsgBox`, 48`, 7zip.exe Error`, %Error%`, 5`nExitApp`n}`nIf (FileExist(7zExtractDir . 7zN . ""."" . A_LoopField) || skipchecks = ""true"") {`n7zE = .%A_LoopField% `nromFound = true`nBreak`n} Else`nromFound = false`n}`n}`nIf ( romFound = ""false"" )`nScriptError(""No extracted files found in "" . 7zExtractDir . ""``nCheck if you are exceeding the 255 character limit."")`n7zP = %7zExtractDir%`n}`n}`n}"


	retStr .= "`n`n7z(ByRef 7zP`, ByRef 7zN`, ByRef 7zE`, ByRef 7zExtractDir){`nGlobal 7zEnable`nGlobal 7zFormats`nGlobal 7zFormatsNoP`nGlobal romExtensions`nGlobal skipchecks`nIf ( 7zEnable = ""true"" ) {`nIf 7zE in %7zFormats%`n{`nCheckForRomExt()`n7zPath = %A_ScriptDir%\7z.exe`n7zList := StdoutToVar_CreateProcess(7zPath . "" l """""" . 7zP . 7zN . 7zE . """""""")`nclipboard = % 7zlist`nLoop`, Parse`, romExtensions`, ``,`n{`nIf A_LoopField in %7zFormatsNoP%`nContinue`n7zExtractDirCheck = %7zExtractDir%HS\%7zN%\`nIfExist`, %7zExtractDirCheck%%7zN%.%A_LoopField%`n{`n7zE = .%A_LoopField%`nromFound = true`n7zExtractDir = %7zExtractDirCheck%`nBreak`n}`nromIn7z := (InStr(7zList`, 7zN . ""."" . A_LoopField) ? (""true"") : (""false""))`nIf ( romIn7z = ""true"" || skipchecks = ""true"" ) {`n7zExtractDir = %7zExtractDirCheck%`nRunWait`, %7zPath% x ""%7zP%%7zN%%7zE%"" -aoa -o""%7zExtractDir%""`,`,Hide`nIf ( ErrorLevel != 0 ) {`nIf ( ErrorLevel = 1 )`nError = Non fatal error`, file may be in use by another application`nElse If ( ErrorLevel = 2 )`nError = Fatal Error`nElse If ( ErrorLevel = 7 )`nError = Command line error`nElse If ( ErrorLevel = 8 )`nError = Not enough memory for operation`nElse If ( ErrorLevel = 255 )`nError = User stopped the process`nElse`nError = Unknown 7zip Error`nMsgBox`, 48`, 7zip.exe Error`, %Error%`, 5`nExitApp`n}`nIf (FileExist(7zExtractDir . 7zN . ""."" . A_LoopField) || skipchecks = ""true"") {`n7zE = .%A_LoopField%`nromFound = true`nBreak`n} Else {`nromFound = false`nfoundExt := ""."" . A_LoopField`n}`n}`n}`nIf ( romFound = ""false"" )`nScriptError(""No extracted files found in "" . 7zExtractDir . ""``nCheck that you are not exceeding the 255 character limit and this file is in the root of your archive:``n"" . 7zN . foundExt`,10)`n7zP = %7zExtractDir%`n}`n}`n}"
	retStr .= "`n`nStdoutToVar_CreateProcess(sCmd`, bStream = False`, sDir = """"`, sInput = """")`n{`nDllCall(""CreatePipe""`, ""UintP""`, hStdInRd `, ""UintP""`, hStdInWr `, ""Uint""`, 0`, ""Uint""`, 0)`nDllCall(""CreatePipe""`, ""UintP""`, hStdOutRd`, ""UintP""`, hStdOutWr`, ""Uint""`, 0`, ""Uint""`, 0)`nDllCall(""SetHandleInformation""`, ""Uint""`, hStdInRd `, ""Uint""`, 1`, ""Uint""`, 1)`nDllCall(""SetHandleInformation""`, ""Uint""`, hStdOutWr`, ""Uint""`, 1`, ""Uint""`, 1)`nVarSetCapacity(pi`, 16`, 0)`nNumPut(VarSetCapacity(si`, 68`, 0)`, si)`nNumPut(0x100	`, si`, 44)`nNumPut(hStdInRd	`, si`, 56)`nNumPut(hStdOutWr`, si`, 60)`nNumPut(hStdOutWr`, si`, 64)`nIf Not	DllCall(""CreateProcess""`, ""Uint""`, 0`, ""Uint""`, &sCmd`, ""Uint""`, 0`, ""Uint""`, 0`, ""int""`, True`, ""Uint""`, 0x08000000`, ""Uint""`, 0`, ""Uint""`, sDir ? &sDir : 0`, ""Uint""`, &si`, ""Uint""`, π)`nExitApp`nDllCall(""CloseHandle""`, ""Uint""`, NumGet(pi`,0))`nDllCall(""CloseHandle""`, ""Uint""`, NumGet(pi`,4))`nDllCall(""CloseHandle""`, ""Uint""`, hStdOutWr)`nDllCall(""CloseHandle""`, ""Uint""`, hStdInRd)`nIf	sInput <>`nDllCall(""WriteFile""`, ""Uint""`, hStdInWr`, ""Uint""`, &sInput`, ""Uint""`, StrLen(sInput)`, ""UintP""`, nSize`, ""Uint""`, 0)`nDllCall(""CloseHandle""`, ""Uint""`, hStdInWr)`nbStream ? (bAlloc:=DllCall(""AllocConsole"")`,hCon:=DllCall(""CreateFile""`,""str""`,""CON""`,""Uint""`,0x40000000`,""Uint""`,bAlloc ? 0 : 3`,""Uint""`,0`,""Uint""`,3`,""Uint""`,0`,""Uint""`,0)) : """"`nVarSetCapacity(sTemp`, nTemp:=bStream ? 64-nTrim:=1 : 4095)`nLoop`nIf	DllCall(""ReadFile""`, ""Uint""`, hStdOutRd`, ""Uint""`, &sTemp`, ""Uint""`, nTemp`, ""UintP""`, nSize:=0`, ""Uint""`, 0)&&nSize`n{`nNumPut(0`,sTemp`,nSize`,""Uchar"")`, VarSetCapacity(sTemp`,-1)`, sOutput.=sTemp`nIf	bStream&&hCon+1`nLoop`nIf	RegExMatch(sOutput`, ""[^\n]*\n""`, sTrim`, nTrim)`nDllCall(""WriteFile""`, ""Uint""`, hCon`, ""Uint""`, &sTrim`, ""Uint""`, StrLen(sTrim)`, ""UintP""`, nSize:=0`, ""Uint""`, 0)&&nSize ? nTrim+=nSize : """"`nElse	Break`n}`nElse	Break`nDllCall(""CloseHandle""`, ""Uint""`, hStdOutRd)`nbStream ? (DllCall(""Sleep""`,""Uint""`,1000)`,hCon+1 ? DllCall(""CloseHandle""`,""Uint""`,hCon) : """"`,bAlloc ? DllCall(""FreeConsole"") : """") : """"`nReturn sOutput`n}"
	retStr .= "`n`nCheckForRomExt() {`nGlobal romExtensions`nGlobal 7zFormatsNoP`nGlobal skipchecks`nIf ( skipchecks != ""true"" ) {`nLoop`, Parse`, romExtensions`, ```,`n{`nIf A_LoopField in %7zFormatsNoP%`n{`nnotFound = 1`nContinue`n} Else`nReturn`n}`nIf notFound = 1`nScriptError(""You did not supply any valid rom extensions to search for in your compressed roms."")`n}`n}"
	retStr .= "`n`n7zCleanUp() {`nGlobal romTable`nGlobal 7zDelTemp`nGlobal 7zExtractDir`nGlobal mgEnabled`nIf 7zDelTemp = true`n{`nromTableExists := IsObject(romTable)`nIf (mgEnabled = ""true""  && romTableExists)`n{`nfor index`, element in romTable`nIf % romTable[A_Index`, 15]`nFileRemoveDir`, % romTable[A_Index`, 15]`, 1`nFileRemoveDir`, %7zExtractDir%`, 1`n} Else`nFileRemoveDir`, %7zExtractDir%`, 1`n}`n}"

}Else{

	;Still have to add blank functions so no error occurs.
	retStr .= "`n`n7z(7zP`, 7zN`, 7zE`, 7zExtractDir){`n}"
	retStr .= "`n`n7zCleanUp() {`n}"
}


;Added by Tastyratz for Winrar support +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+----------
;Added by Tastyratz for Winrar support +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+----------

If rarEnable = true
{
	retStr .= "`n`nrar(ByRef rarP`, ByRef rarN`, ByRef rarE`, ByRef rarExtractDir){`nGlobal rarEnable`nGlobal rarFormats`nGlobal rarFormatsNoP`nGlobal romExtensions`nGlobal skipchecks`nIf ( rarEnable = ""true"" ) {`nIf rarE in %rarFormats%`n{`nCheckForRomExt()`nrarPath = %A_ScriptDir%\unrar.exe`nrarList := StdoutToVar_CreateProcess(rarPath . "" l """""" . rarP . rarN . rarE . """""""")`nclipboard = % rarlist`nLoop`, Parse`, romExtensions`, ``,`n{`nIf A_LoopField in %rarFormatsNoP%`nContinue`nrarExtractDirCheck = %rarExtractDir%HS\%rarN%\`nIfExist`, %rarExtractDirCheck%%rarN%.%A_LoopField%`n{`nrarE = .%A_LoopField%`nromFound = true`nrarExtractDir = %rarExtractDirCheck%`nBreak`n}`nromInrar := (InStr(rarList`, rarN . ""."" . A_LoopField) ? (""true"") : (""false""))`nIf ( romInrar = ""true"" || skipchecks = ""true"" ) {`nrarExtractDir = %rarExtractDirCheck%`nRunWait`, %rarPath% x -ad -o+ ""%rarP%%rarN%%rarE%"" ""%rarExtractDir%""`,`,Hide`nIf ( ErrorLevel != 0 ) {`nIf ( ErrorLevel = 1 )`nError = Non fatal error`, file may be in use by another application`nElse If ( ErrorLevel = 2 )`nError = Fatal Error`nElse If ( ErrorLevel = 7 )`nError = Command line error`nElse If ( ErrorLevel = 8 )`nError = Not enough memory for operation`nElse If ( ErrorLevel = 255 )`nError = User stopped the process`nElse`nError = Unknown unrar Error`nMsgBox`, 48`, unrar.exe Error`, %Error%`, 5`nExitApp`n}`nIf (FileExist(rarExtractDir . rarN . ""."" . A_LoopField) || skipchecks = ""true"") {`nrarE = .%A_LoopField%`nromFound = true`nBreak`n} Else {`nromFound = false`nfoundExt := ""."" . A_LoopField`n}`n}`n}`nIf ( romFound = ""false"" )`nScriptError(""No extracted files found in "" . rarExtractDir . ""``nCheck that you are not exceeding the 255 character limit and this file is in the root of your archive:``n"" . rarN . foundExt`,10)`nrarP = %rarExtractDir%`n}`n}`n}"

	retStr .= "`n`nStdoutToVar_CreaterarProcess(sCmd`, bStream = False`, sDir = """"`, sinput = """")`n{`nDllCall(""CreatePipe""`, ""UintP""`, hStdInRd `, ""UintP""`, hStdInWr `, ""Uint""`, 0`, ""Uint""`, 0)`nDllCall(""CreatePipe""`, ""UintP""`, hStdOutRd`, ""UintP""`, hStdOutWr`, ""Uint""`, 0`, ""Uint""`, 0)`nDllCall(""SetHandleInformation""`, ""Uint""`, hStdInRd `, ""Uint""`, 1`, ""Uint""`, 1)`nDllCall(""SetHandleInformation""`, ""Uint""`, hStdOutWr`, ""Uint""`, 1`, ""Uint""`, 1)`nVarSetCapacity(pi`, 16`, 0)`nNumPut(VarSetCapacity(si`, 68`, 0)`, si)`nNumPut(0x100	`, si`, 44)`nNumPut(hStdInRd	`, si`, 56)`nNumPut(hStdOutWr`, si`, 60)`nNumPut(hStdOutWr`, si`, 64)`nIf Not	DllCall(""CreateProcess""`, ""Uint""`, 0`, ""Uint""`, &sCmd`, ""Uint""`, 0`, ""Uint""`, 0`, ""int""`, True`, ""Uint""`, 0x08000000`, ""Uint""`, 0`, ""Uint""`, sDir ? &sDir : 0`, ""Uint""`, &si`, ""Uint""`, π)`nExitApp`nDllCall(""CloseHandle""`, ""Uint""`, NumGet(pi`,0))`nDllCall(""CloseHandle""`, ""Uint""`, NumGet(pi`,4))`nDllCall(""CloseHandle""`, ""Uint""`, hStdOutWr)`nDllCall(""CloseHandle""`, ""Uint""`, hStdInRd)`nIf	sinput <>`nDllCall(""WriteFile""`, ""Uint""`, hStdInWr`, ""Uint""`, &sinput`, ""Uint""`, StrLen(sinput)`, ""UintP""`, nSize`, ""Uint""`, 0)`nDllCall(""CloseHandle""`, ""Uint""`, hStdInWr)`nbStream ? (bAlloc:=DllCall(""AllocConsole"")`,hCon:=DllCall(""CreateFile""`,""str""`,""CON""`,""Uint""`,0x40000000`,""Uint""`,bAlloc ? 0 : 3`,""Uint""`,0`,""Uint""`,3`,""Uint""`,0`,""Uint""`,0)) : """"`nVarSetCapacity(sTemp`, nTemp:=bStream ? 64-nTrim:=1 : 4095)`nLoop`nIf	DllCall(""ReadFile""`, ""Uint""`, hStdOutRd`, ""Uint""`, &sTemp`, ""Uint""`, nTemp`, ""UintP""`, nSize:=0`, ""Uint""`, 0)&&nSize`n{`nNumPut(0`,sTemp`,nSize`,""Uchar"")`, VarSetCapacity(sTemp`,-1)`, sOutput.=sTemp`nIf	bStream&&hCon+1`nLoop`nIf	RegExMatch(sOutput`, ""[^\n]*\n""`, sTrim`, nTrim)`nDllCall(""WriteFile""`, ""Uint""`, hCon`, ""Uint""`, &sTrim`, ""Uint""`, StrLen(sTrim)`, ""UintP""`, nSize:=0`, ""Uint""`, 0)&&nSize ? nTrim+=nSize : """"`nElse	Break`n}`nElse	Break`nDllCall(""CloseHandle""`, ""Uint""`, hStdOutRd)`nbStream ? (DllCall(""Sleep""`,""Uint""`,1000)`,hCon+1 ? DllCall(""CloseHandle""`,""Uint""`,hCon) : """"`,bAlloc ? DllCall(""FreeConsole"") : """") : """"`nReturn sOutput`n}"

	retStr .= "`n`nCheckForRomExtrar() {`nGlobal romExtensions`nGlobal rarFormatsNoP`nGlobal skipchecks`nIf ( skipchecks != ""true"" ) {`nLoop`, Parse`, romExtensions`, ```,`n{`nIf A_LoopField in %rarFormatsNoP%`n{`nnotFound = 1`nContinue`n} Else`nReturn`n}`nIf notFound = 1`nScriptError(""You did not supply any valid rom extensions to search for in your compressed roms."")`n}`n}"

	retStr .= "`n`nrarCleanUp() {`nGlobal romTable`nGlobal rarDelTemp`nGlobal rarExtractDir`nGlobal mgEnabled`nIf rarDelTemp = true`n{`nromTableExists := IsObject(romTable)`nIf (mgEnabled = ""true""  && romTableExists)`n{`nfor index`, element in romTable`nIf % romTable[A_Index`, 15]`nFileRemoveDir`, % romTable[A_Index`, 15]`, 1`nFileRemoveDir`, %rarExtractDir%`, 1`n} Else`nFileRemoveDir`, %rarExtractDir%`, 1`n}`n}"
}Else{
	;Still have to add blank functions so no error occurs.
	retStr .= "`n`nrar(rarP`, rarN`, rarE`, rarExtractDir){`n}"
	retStr .= "`n`nrarCleanUp() {`n}"
}

;Added by Tastyratz for Winrar support +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+----------
;Added by Tastyratz for Winrar support +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+----------





;Add MultiGame labels and functions if needed by the system
If mgEnabled = true
	retStr .= "`n`nStartMulti:`nHotkey`, %mgKey%`, Off`nmultiTypes = (Cart`,(Disc`,(Disk`,(Tape`ncurrentButton:=1`nmgCancel:=0`nangle:=0`nb:=1`nmgGrowing:=`n`nIf romName not contains %multiTypes%`nReturn`nIf romExtensionOrig contains %7zFormats%`nIf % 7zEnable = ""true""`nromNeeds7z:=1`n`nIf !romTable`nromTable:=CreateRomTable(romName)`n`nIf !romTable.MaxIndex() {`nToolTip`, This game does not need Multi-Game support`, 0`, 0`nSleep`, 1000`nToolTip`nReturn`n}`n`nIf !pToken := Gdip_Startup()`n{`nScriptError(""Gdiplus failed to start. Please ensure you have gdiplus on your system"")`nExitApp`n}`n`nGosub`, PreMultiGame`n`nmgW := A_ScreenWidth`, mgH := A_ScreenHeight`nLoop`, 2 {`nGui`, %A_Index%: -Caption +E0x80000 +LastFound +OwnDialogs +Owner +AlwaysOnTop`nGui`, %A_Index%: Margin`,0`,0`nGui`, %A_Index%: Show`,`, Layer%A_Index%`nhwnd%A_Index% := WinExist()`n`nhbm%A_Index% := CreateDIBSection(mgW`, mgH)`, hdc%A_Index% := CreateCompatibleDC()`, obm%A_Index% := SelectObject(hdc%A_Index%`, hbm%A_Index%)`nG%A_Index% := Gdip_GraphicsFromhdc(hdc%A_Index%)`n}`nGdip_SetInterpolationMode(G1`, 7)`n`nIf !hFamily := Gdip_FontFamilyCreate(mgFont)`n{`nScriptError(""The mgFont "" . mgFont . "" you have specified does not exist on the system"")`nExitApp`n}`nGdip_DeleteFontFamily(hFamily)`n`nIfExist`, % multiGameImgPath . romName . "".png""`nmultiBG:=multiGameImgPath . romName . "".png""`nElse IfExist`, % multiGameImgPath . ""default.png""`nmultiBG:=multiGameImgPath . ""default.png""`nElse`nmultiBG:=`n`nLoop`, 2 {`nImage_%A_Index% := multiGameImgPath . romTable[A_Index`,5] . ""_image_"" . A_Index . "".png""`nIf !FileExist(Image_%A_Index%) {`nToolTip`, Downloading Image %A_Index%`,0`,0`nIfNotExist`, % multiGameImgPath`nFileCreateDir`, % multiGameImgPath`nUrlDownloadToFile`, % ""http://www.hyperspin-fe.com/HL2/"" . romTable[A_Index`,5] . ""_image_"" . A_Index . "".png""`, % multiGameImgPath . romTable[A_Index`,5] . ""_image_"" . A_Index . "".png""`nIf ErrorLevel`nScriptError(""Error connecting to www.hyperspin-fe.com to download images. Please try again later or report the problem it it persists."")`n}`nToolTip`n}`n`nfor index`, element in romTable`n{`nIf FileExist(A_ScriptDir . ""\Media\"" . systemName . ""\Images\"" . mgArtworkDir . ""\"" . romTable[A_Index`, 3] . "".png"") && (mgUseGameArt = ""true"" ) {`nromTable[A_Index`, 13] := Gdip_CreateBitmapFromFile(A_ScriptDir . ""\Media\"" . systemName . ""\Images\"" . mgArtworkDir . ""\"" . romTable[A_Index`, 3] . "".png"")`nIf !romTable[A_Index`, 13] {`nMsgBox`, 16`, Error Loading MultiGame Artwork %A_Index%`, % ""Could not find "" .  romTable[A_Index`,3] . "".png. Please try again later or report the problem if it persists.""`,5`nGoto`, MGExit`n}`nromTable[A_Index`,12] := ""Yes""`n} Else {`nromTable[A_Index`, 13] := Gdip_CreateBitmapFromFile(Image_1)`nromTable[A_Index`, 14] := Gdip_CreateBitmapFromFile(Image_2)`n}`nGdip_GetImageDimensions(romTable[A_Index`, 13]`, mgArtW`, mgArtH)`nromTable[A_Index`,8] := mgArtW`, romTable[A_Index`,9] := mgArtH`nromTable[A_Index`,10] := romTable[A_Index`,8]*mgImageAdjust`, romTable[A_Index`,11] := romTable[A_Index`,9]*mgImageAdjust`nIf mgSelectedEffect = rotate`n{`nGdip_GetRotatedDimensions(romTable[A_Index`, 10]`, romTable[A_Index`, 11]`, 90`, mgRW%A_Index%`, mgRH%A_Index%)`nmgRW%A_Index% := (mgRW%A_Index% > romTable[A_Index`, 10]) ? mgRW%A_Index%* : romTable[A_Index`, 10]`, mgRH%A_Index% := (mgRH%A_Index% > romTable[A_Index`, 11]) ? mgRH%A_Index% : romTable[A_Index`, 11]`n}`n}`n`ntotalUnusedWidth := mgW - ( romTable[1`, 10] * romTable.MaxIndex() )`nremainingUnusedWidth := totalUnusedWidth * ( 1 - ( mgSidePadding * 2 ))`npaddingSpotsNeeded := romTable.MaxIndex() - 1`nimageSpacing := remainingUnusedWidth//paddingSpotsNeeded`nimageX:=mgSidePadding * totalUnusedWidth`nimageXcurrent:=imageX`n`nIf MultiBG {`nmBGBitmap := Gdip_CreateBitmapFromFile(multiBG)`nGdip_GetImageDimensions(mBGBitmap`, mBGw`, mBGh)`nGdip_DrawImage(G1`, mBGBitmap`, 0`, 0`, mgW+1`, mgH+1`, 0`, 0`, mBGw`, mBGh)`n} Else {`npBrush := Gdip_BrushCreateSolid(""0x"" . mgBackgroundColor)`nGdip_FillRectangle(G1`, pBrush`, -1`, -1`, mgW+1`, mgH+1)`n}`n`nGdip_TextToGraphics(G1`, mgText1Text`, mgText1Options`, mgFont`, mgW`, mgH)`n`nfor index`, element in romTable {`nromTable[A_Index`,6] := (If romTable[A_Index`,12] ? (imageXcurrent) : (imageXcurrent+(romTable[1`,10]//2-romTable[A_Index`,10]//2)))`nromTable[A_Index`,7] := mgH - mgYOffset`nGdip_DrawImage(G1`, romTable[A_Index`, 13]`, romTable[A_Index`,6]`, mgH - mgYOffset`, romTable[1`,10]`, romTable[A_Index`,11]`, 0`, 0`, romTable[1`,10]//mgImageAdjust`, romTable[A_Index`,11]//mgImageAdjust)`nGdip_TextToGraphics(G1`, romTable[A_Index`,4]`, ""x"" . imageXcurrent . "" y"" . mgH-mgYOffset-mgText2Offset . "" "" . mgText2Options`, mgFont`, romTable[1`,10]`, romTable[A_Index`,11])`nmgArt%A_Index%X := imageXcurrent`nIf ( A_index <= paddingSpotsNeeded )`nimageXcurrent:=imageXcurrent+ romTable[1`,10]+imageSpacing`n}`n`nUpdateLayeredWindow(hwnd1`, hdc1`, 0`, 0`, mgW`, mgH)`nSetTimer`,Update`,30`n`nHotkey`,IfWinActive`,Layer ahk_class AutoHotkeyGUI`nHotkey`,UP`,Forward`nHotkey`,Down`,Backward`nHotkey`,Left`,Forward`nHotkey`,Right`,Backward`nHotkey`,%mgSelectKey%`,SelectGame`nHotkey`,%mgExitKey%`,MGCancel`nHotkey`,LButton`,MouseBlank`nHotkey`,RButton`,MouseBlank`nHotkey`,MButton`,MouseBlank`nReturn`n`nForward:`nIf (mgUseSound=""true"")`nSoundBeep`,%mgSoundfreq%`,10`nIf (mgSelectedEffect = ""grow"") {`nGdip_GraphicsClear(G2)`nmgGrowing:=`nb := 1`n}`nangle:=0`nold_currentButton:=currentButton`nIf (currentButton>1)`ncurrentButton:=currentButton-1`nElse`ncurrentButton:=romTable.MaxIndex()`nReturn`n`nBackward:`nIf (mgUseSound=""true"")`nSoundBeep`,%mgSoundfreq%`,10`nIf (mgSelectedEffect = ""grow"") {`nGdip_GraphicsClear(G2)`nmgGrowing:=`nb := 1`n}`nangle:=0`nold_currentButton:=currentButton`nIf (currentButton<romTable.MaxIndex())`ncurrentButton:=currentButton+1`nElse`ncurrentButton:=1`nReturn`n`nMouseBlank:`nReturn`n`nUpdate:`nIfWinNotActive`,Layer2 ahk_class AutoHotkeyGUI`nWinActivate`,Layer2 ahk_class AutoHotkeyGUI`nGdip_GraphicsClear(G2)`nIf (mgSelectedEffect = ""rotate"" && romTable[currentButton`, 12]) {`nangle := (angle > 360) ? 2 : angle+2`nGdip_ResetWorldTransform(G2)`nGdip_TranslateWorldTransform(G2`, mgRW%currentButton%//2`, mgRH%currentButton%//2)`nGdip_RotateWorldTransform(G2`, angle)`nGdip_TranslateWorldTransform(G2`, -mgRW%currentButton%//2`, -mgRH%currentButton%//2)`nGdip_DrawImage(G2`, romTable[currentButton`, 13]`, (mgRW%currentButton%-romTable[currentButton`, 10])`, (mgRH%currentButton%-romTable[currentButton`, 11])`, romTable[currentButton`, 10]`, romTable[currentButton`, 11])`nUpdateLayeredWindow(hwnd2`, hdc2`, romTable[currentButton`, 6]-1`, romTable[currentButton`, 7]-1`, mgRW%currentButton%`, mgRH%currentButton%)`nReturn`n} Else If (mgSelectedEffect = ""rotate"" && !romTable[currentButton`, 12]) {`nGdip_ResetWorldTransform(G2)`nGdip_DrawImage(G2`, romTable[currentButton`, 14]`, romTable[currentButton`, 6]`,  romTable[currentButton`, 7]`, romTable[currentButton`,10]`, romTable[currentButton`,11]`, 0`, 0`, romTable[currentButton`,10]//mgImageAdjust`, romTable[currentButton`,11]//mgImageAdjust)`n} Else If (mgSelectedEffect = ""grow"") {`nSleep`, 5`nIf !mgGrowing`nSetTimer`, MGGrow`, -1`nReturn`n}`nUpdateLayeredWindow(hwnd2`, hdc2`, 0`, 0`, mgW`, mgH)`nReturn`n`nMGGrow:`nmgGrowing:=1`nWhile b <= 30 {`nGdip_DrawImage(G2`, (If romTable[currentButton`, 12] ? (romTable[currentButton`, 13]):(romTable[currentButton`, 14]))`, romTable[currentButton`,6]-(b//2)`,  romTable[currentButton`,7]-(b//2)`, romTable[currentButton`,10]+b`, romTable[currentButton`,11]+b`, 0`, 0`, romTable[currentButton`,10]//mgImageAdjust`, romTable[currentButton`,11]//mgImageAdjust)`nUpdateLayeredWindow(hwnd2`, hdc2`, 0`, 0`, mgW`, mgH)`nb+=2`n}`nReturn`n`nSelectGame:`nSetTimer`,Update`, Off`nIf mgExitEffect {`nv := 1`nb+=2`nIf mgSelectedEffect = rotate`n{`nGdip_GraphicsClear(G2)`nGdip_ResetWorldTransform(G2)`nUpdateLayeredWindow(hwnd2`, hdc2`, 0`, 0`, mgW`, mgH)`n}`nLoop`, 25 {`nIf mgExitEffect = pixelate`n{`nmgArtOut := Gdip_CreateBitmap(romTable[currentButton`, 10]//mgImageAdjust`, romTable[currentButton`, 11]//mgImageAdjust)`nIf romTable[currentButton`, 12] {`nGdip_PixelateBitmap(romTable[currentButton`, 13]`, mgArtOut`,++v)`nGdip_DrawImage(G2`, mgArtOut`, romTable[currentButton`, 6]-(b//2)`, romTable[currentButton`, 7]-(b//2)`, romTable[currentButton`, 10]+b`, romTable[currentButton`, 11]+`n} Else {`nGdip_PixelateBitmap(romTable[currentButton`, 14]`, mgArtOut`,++v)`nGdip_DrawImage(G2`, mgArtOut`, romTable[currentButton`, 6]`, romTable[currentButton`, 7]`, romTable[currentButton`, 10]`, romTable[currentButton`, 11]`, 0`, 0`, romTable[currentButton`, 10]//mgImageAdjust`, romTable[currentButton`, 11]//mgImageAdjust)`n}`n} Else If mgExitEffect = grow`n{`nGdip_DrawImage(G2`, (If romTable[currentButton`, 12] ? (romTable[currentButton`, 13]):(romTable[currentButton`, 14]))`, romTable[currentButton`, 6]-(b//2)-(v//2)`, romTable[currentButton`, 7]-(b//2)-(v//2)`, romTable[currentButton`, 10]+b+v`, romTable[currentButton`, 11]+b+v`, 0`, 0`, romTable[currentButton`, 10]//mgImageAdjust`, romTable[currentButton`, 11]//mgImageAdjust)`n}`nUpdateLayeredWindow(hwnd2`, hdc2)`nv+=2`n}`n}`nselectedRom:=romTable[currentButton`,1]`nSplitPath`, selectedRom`,`,mgRomPath`,mgRomExt`,mgRomName`nIf romNeeds7z {`nmgRomExt:=""."" . mgRomExt`n7z%currentButton% := 7z(mgRomPath`, mgRomName`, mgRomExt`, 7zExtractDir)`nromTable[currentButton`,15]:=mgRomPath . mgRomName`n}`nGoto`, MGExit`n`nMGCancel:`nmgCancel:=1`nMGExit:`nHotkey`, IfWinActive`nSetTimer`,Update`, Off`nToolTip`nGdip_DeleteBrush(pBrush)`nfor index`, element in romTable`nGdip_DisposeImage(romTable[currentButton`,13])`, Gdip_DisposeImage(romTable[currentButton`,14])`nIf mgExitEffect = pixelate`nGdip_DisposeImage(mgArtOut)`nLoop`, 2 {`nSelectObject(hdc%A_Index%`, obm%A_Index%)`, DeleteObject(hbm%A_Index%)`, DeleteDC(hdc%A_Index%)`nGui`, %A_Index%: Destroy`n}`nGdip_Shutdown(pToken)`nSleep`, 1000`nHotkey`, %exitEmulatorKey%`, CloseProcess`, On`nHotkey`, %mgKey%`, StartMulti`, On`nGoto`, MultiGame`nReturn`n`nCreateRomTable(rom) {`nGlobal romPathFromIni`nGlobal romName`nGlobal romExtensionOrig`nGlobal 7zEnable`nromCount:=0`nromTable:=[]`ntypeArray := [""(Cart""`,""(Disc""`,""(Disk""`,""(Tape""]`nregExCheck = \s\(Disc\s[^/]*|\s\(Disk\s[^/]*|\s\(Cart\s[^/]*|\s\(Tape\s[^/]*`nromNamePre:=RegExReplace(romName`, regExCheck)`nLoop % typeArray.MaxIndex()`nIf rom contains % typeArray[A_Index]`n{`nLoop`, % romPathFromIni . romNamePre . A_Space . typeArray[A_Index] . ""*""`, 1`,1`n{`nIf romExtensionOrig contains % A_LoopFileExt`n{`nromCount+=1`nromTable[romCount`,1]:=A_LoopFileFullPath`nromTable[romCount`,2]:=A_LoopFileName`nromTable[romCount`,3] := RegExReplace(romTable[romCount`, 2]`, ""\..*"")`npos := RegExMatch(romTable[romCount`,2]`, regExCheck)`nuncleanTxt:= SubStr(romTable[romCount`,2]`, pos + 1)`nromTable[romCount`,4] := RegExReplace(uncleanTxt`, ""\(|\)|\..*"")`nromTable[romCount`,5] := SubStr(romTable[romCount`,4]`,1`,4)`n}`n}`n}`nReturn romTable`n}"

; Add CheckFile and ScriptError functions for the modules that use them.
retStr .= "`n`nCheckFile(file`,msg=""""`,timeout=6){`nIfNotExist`, %file%`n{`nIf msg`nScriptError(msg`, timeout)`nElse`nScriptError(""Cannot find "" . file`, timeout) `n}`nReturn %file%`n}"
retStr .= "`n`nScriptError(error`,timeout=6){`nMsgBox`,48`,Error`,%error%`,%timeout%`nExitApp`n}"

Log("Finished injecting functions into module")

If debugModule = 1
{
	Gui, 2:+Resize
	Gui, 2:+owner
	Gui +Disabled
	Gui, 2:Add, edit,r27 w585 readonly -E0x200, %retStr%
	Gui, 2:Add, Button, Default, OK
	Gui, 2:Show
	Gui, 2:Show, Center h400 w600, Debug Module
	Pause
}

Return retStr
}

2ButtonOK:
Gui, 1:-Disabled
Gui, 2:Destroy
Pause
Return

CheckFile(file,msg="",timeout=6){
IfNotExist, %file%
{
	If msg
		ScriptError(msg, timeout)
	Else
		ScriptError("Cannot find " . file, timeout)
}
Return %file%
}

ScriptError(error,timeout=6){
MsgBox,48,Error,%error%,%timeout%
Log(error)
ExitScript()
}

checkPaths(){
Global executable
Global romPath
Global emuPath
Global romExtensions
Global romExtension
Global systemName
Global romName
Global 7zExtractDir
Global 7zEnable
Global rarExtractDir
Global rarEnable
Global keymapperEnabled
Global keymapperProfilePath

Log("Checking paths")
romFound = 
StringRight, emuPathBackSlash, emuPath, 1
StringRight, romPathBackSlash, romPath, 1
StringRight, 7zExtractDirBackSlash, 7zExtractDir, 1
StringRight, rarExtractDirBackSlash, rarExtractDir, 1
StringRight, keymapperProfilePathBackSlash, keymapperProfilePath, 1

If (emuPath = "")
	ScriptError("Missing path in ini.")

If (emuPathBackSlash != "\" || romPathBackSlash != "\") || (7zEnable = "true" && 7zExtractDirBackSlash != "\" ) || (keymapperEnabled = "true" && keymapperProfilePathBackSlash != "\" )
	ScriptError("Make sure your paths contains a backslash on the end.")

If (emuPathBackSlash != "\" || romPathBackSlash != "\") || (rarEnable = "true" && rarExtractDirBackSlash != "\" ) || (keymapperEnabled = "true" && keymapperProfilePathBackSlash != "\" )
	ScriptError("Make sure your paths contains a backslash on the end.")

If (executable = "") 
	ScriptError("Missing executable in ini.")

If (romPath = "") 
	ScriptError("Missing rompath in ini.")

If (romExtensions = "")
	ScriptError("Missing rom extension in ini.")

If ( 7zEnable = "true" ) {
	checkFile(A_ScriptDir . "\7z.exe")
	checkFile(A_ScriptDir . "\7z.dll")
}
If ( rarEnable = "true" ) {
	checkFile(A_ScriptDir . "\unrar.exe")
}

checkFile(emuPath . executable)

If (systemName != "zinc"){
	Loop, parse, romExtensions, `,
	{
		inputVar = %A_LoopField%
		StringLeft, charToCheck, inputVar, 1
		If (charToCheck = ".")
		ScriptError("Make sure your rom extensions do not contain a .")

		IfExist %romPath%%romName%.%A_LoopField%
		{
			romExtension = .%A_LoopField% 
			romFound = true
			break
		}Else{
			IfExist %romPath%%romName%\%romName%.%A_LoopField%
			{
				romPath = %romPath%%romName%\
				romExtension = .%A_LoopField% 
				romFound = true
				break	   
			}Else{
				romFound = false
			}
		}
	}

	If ( 7zExtractDir = "" && 7zEnable = "true" )
		ScriptError("You are asking 7z to extract your ROMs. Your ROM's extension is " . romExtension . "`, but you did not specifiy a 7zExtractDir in the '" . systemName . ".ini' to extract to.")

	If ( rarExtractDir = "" && rarEnable = "true" )
		ScriptError("You are asking UNRAR to extract your ROMs. Your ROM's extension is " . romExtension . "`, but you did not specifiy a rarExtractDir in the '" . systemName . ".ini' to extract to.")
}

If (romFound = "false")
{
	If (systemName != "daphne"){
		ScriptError("Cannot find Rom - " . romPath . romName . " with any provided extension")
	}Else{
		ScriptError("Cannot find Daphne framefile - " . romPath . romName . " with any provided extension")
	}
}
Return romExtension
}

GetExtensions(){
Global romExtensions
Global romPath
Global romExtensions
Global romName
Log("Getting extensions")
Loop, parse, romExtensions, `,
{
	inputVar = %A_LoopField%
	StringLeft, charToCheck, inputVar, 1
	If (charToCheck = ".")
	ScriptError("Make sure your rom extensions do not contain a .")

	IfExist %romPath%%romName%.%A_LoopField%
	{
		romExtension = .%A_LoopField% 
		romFound = true
		break
	}Else{
		IfExist %romPath%%romName%\%romName%.%A_LoopField%
		{
			romPath = %romPath%%romName%\
			romExtension = .%A_LoopField% 
			romFound = true
			break	   
		}Else{
			romFound = false
		}
	}
}
Return romExtension
}

GetSystems(){
Static systemName
Static systems
Static ArrayCount = 1
Global lastSystem

systemsFile := checkFile(A_ScriptDir . "\Databases\Main Menu\Main Menu.xml")
Loop, read, %systemsFile%
{   
	pos := RegExMatch(A_LoopReadLine,"name=""(.*)""", SubPat)
	If (pos > 1){
		systems%ArrayCount% := SubPat1
		ArrayCount += 1
	}
}
ArrayCount -= 1

If (lastSystem != ""){
	elements := lastSystem . "||"
}Else{
	elements := "||"
}

Loop %ArrayCount%
{
	elements .= systems%A_Index% . "|"
}  

Gui, Add, ComboBox, x12 y100 w266 vEdit1, %elements%
}

GetFullName( fn ) {
; http://msdn.microsoft.com/en-us/library/Aa364963
; msgbox, %fn%
Static buf, i
If !i
	i := VarSetCapacity(buf, 512)
; msgbox, %buf%
DllCall("GetFullPathNameA", "str", fn, "uint", 512, "str", buf, "str*", 0)
; msgbox, %buf%
Return buf
}

SystemCursor(OnOff=1)   ; INIT = "I","Init"; OFF = 0,"Off"; TOGGLE = -1,"T","Toggle"; ON = others
{
Static AndMask, XorMask, $, h_cursor
	,c0,c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13 ; system cursors
	, b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13   ; blank cursors
	, h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11,h12,h13   ; handles of default cursors
If (OnOff = "Init" or OnOff = "I" or $ = "")	   ; init when requested or at first call
{
	$ = h	; active default cursors
	VarSetCapacity( h_cursor,4444, 1 )
	VarSetCapacity( AndMask, 32*4, 0xFF )
	VarSetCapacity( XorMask, 32*4, 0 )
	system_cursors = 32512,32513,32514,32515,32516,32642,32643,32644,32645,32646,32648,32649,32650
	StringSplit c, system_cursors, `,
	Loop %c0%
	{
		h_cursor   := DllCall( "LoadCursor", "uint",0, "uint",c%A_Index% )
		h%A_Index% := DllCall( "CopyImage",  "uint",h_cursor, "uint",2, "int",0, "int",0, "uint",0 )
		b%A_Index% := DllCall("CreateCursor","uint",0, "int",0, "int",0
			, "int",32, "int",32, "uint",&AndMask, "uint",&XorMask )
	}
}
If (OnOff = 0 or OnOff = "Off" or $ = "h" and (OnOff < 0 or OnOff = "Toggle" or OnOff = "T"))
	$ = b	; use blank cursors
Else
	$ = h	; use the saved cursors

Loop %c0%
{
	h_cursor := DllCall( "CopyImage", "uint",%$%%A_Index%, "uint",2, "int",0, "int",0, "uint",0 )
	DllCall( "SetSystemCursor", "uint",h_cursor, "uint",c%A_Index% )
}
}


LoadKeyMapper(byref MScript) {
Global
; msgbox, LoadKeyMapper Function`nkeymapper=%keymapper%`nhyperspinProfile=%hyperspinProfile%`nkeymapperExe=%keymapperExe%`nkeymapperPath=%keymapperPath%
; Build profile
If (keymapper="xpadder")
	hyperspinProfile := hyperspinProfile . ".xpadderprofile", defaultProfile := defaultProfile . ".xpadderprofile", systemProfile := systemProfile . ".xpadderprofile", romProfile := romProfile . ".xpadderprofile"
Else If (keymapper="joytokey")
	hyperspinProfile := hyperspinProfile . ".cfg", defaultProfile := defaultProfile . ".cfg", systemProfile := systemProfile . ".cfg", romProfile := romProfile . ".cfg"
Else If (keymapper="ahk")
	hyperspinProfile := hyperspinProfile . ".ahk", defaultProfile := defaultProfile . ".ahk", systemProfile := systemProfile . ".ahk", romProfile := romProfile . ".ahk"
Else
	ScriptError("Keymapper support is enabled`, but you set keymapper to """ . keymapper . """ which is not a valid option.")

If (FileExist(romProfile))
	profileToUse=%romProfile%
Else If (FileExist(systemProfile))
	profileToUse=%systemProfile%
Else If (FileExist(defaultProfile))
	profileToUse=%defaultProfile%
Else If (FileExist(hyperspinProfile))
	profileToUse=%hyperspinProfile%
Else
	ScriptError("Keymapper support is enabled for """ . keymapper . """`, but could not find a valid HyperSpin`, default`, " . systemName . "`, or " . romName . " profile in " . keymapperProfilePath . ".")

Log("Launching " . keymapper . " and first profile found = " . profileToUse)

; Launch keymapper
If (keymapper="xpadder") {
	SplitPath, profileToUse,, profileDir, profileExt, profileName ; need to splitpath again so we can find profiles for player 2+
	arProfileNames = | [p2]| [p3]| [p4]
	Loop, Parse, arProfileNames, |
	{
		If (FileExist(profileDir . "\" . profileName . A_LoopField . "." . profileExt))
			profile%A_Index% = %profileDir%\%profileName%%A_LoopField%.%profileExt%
	}
	RunXpadder(profile1,profile2,profile3,profile4)
} Else If (keymapper="joytokey") {
	IniRead, exitMeansMinimize, %keymapperPath%\JoyToKey.ini, LastStatus, ExitMeansMinimize ; checking if user has this option disabled, otherwise joytokey will not close with WinClose
	If ( exitMeansMinimize = "ERROR" )
		ScriptError("You are using KeyMapper support but are not up-to-date with JoyToKey or cannot find JoyToKey.ini in " . keymapperPath . "`nPlease make sure you are running JoyToKey v5.1.0 or later",10)
	Else If ( exitMeansMinimize = 1 ) {
		Process, Close, %keymapperExe% ; forcing JoyToKey closed because we need it running with the above option disabled to function properly
		Process, WaitClose, %keymapperExe% ; Make sure it's actually closed before continuing
		IniWrite, 0, %keymapperPath%\JoyToKey.ini, LastStatus, ExitMeansMinimize ; disabling this setting for user
	}
	WinClose, JoyToKey ahk_class TMainForm
	Process, WaitClose, %keymapperExe%,1 ; Make sure it's actually closed before continuing
	If ErrorLevel
		Process, Close, %keymapperExe% ; user possibly re-enabled the above option, closing it to continue script
	Log("Run, " . keymapperExe .  " """ . profileToUse . """, " . keymapperPath)
	Run, %keymapperExe% "%profileToUse%", %keymapperPath% ; Run joytokey
} Else If (keymapper="ahk") {
	Loop, Read, %profileToUse% ; Adding ahk remaps to the bottom of our module
		MScript .= "`n" . A_LoopReadLine
	; msgbox, %MScript%
}
Return hyperspinProfile
}

RunXpadder(profile1,profile2="",profile3="",profile4="") {
Global keymapperExe
Global keymapperPath
Log("Run, " . keymapperExe .  " """ . profile1 . """ """ . profile2 . """ """ . profile3 . """ """ . profile4 . """ /M, " . keymapperPath)
Run, %keymapperExe% "%profile1%" "%profile2%" "%profile3%" "%profile4%" /M, %keymapperPath%
}

BuildAhkRemap(profiles) {
Static retAhk
; moduleFile := checkFile(A_ScriptDir . "\Modules\" . moduleName . "\" . moduleName . ".ahk")
Loop, Parse, profiles, | ; Reading each profile, one at a time
{
	Loop, Read, %A_LoopField% ; Building ahk remaps into one big script
	{
		retAhk .= "`n" . A_LoopReadLine
	}
}
}

UnloadKeyMapper() {
;Unload keymapper or load HyperSpin profile if it exists
Global
Log("Unloading " . keymapper)
If (keymapper="xpadder") {
	If (FileExist(hyperspinProfile)) {
		SplitPath, hyperspinProfile,, hDir, hExt, hName ; need to splitpath again so we can find profiles for player 2+
		arProfileNames = | [p2]| [p3]| [p4]
		Loop, Parse, arProfileNames, |
		{
			If (FileExist(hDir . "\" . hName . A_LoopField . "." . hExt))
				hProfile%A_Index% = %hDir%\%hName%%A_LoopField%.%hExt%
		}
		RunXpadder(hProfile1,hProfile2,hProfile3,hProfile4)
	} Else {
		Log("Run, " . keymapperExe .  " /C, " . keymapperPath)
		Run, %keymapperExe% /C, %keymapperPath% ; or close if HyperSpin profile doesn't exist
	}
} Else If (keymapper="joytokey") {
	If (FileExist(hyperspinProfile)){
		WinClose, JoyToKey ahk_class TMainForm
		Process, WaitClose, %keymapperExe% ; Make sure it's actually closed before continuing
		Log("Run, " . keymapperExe .  " """ . hyperspinProfile . ".cfg"", " . keymapperPath)
		Run, %keymapperExe% "%hyperspinProfile%.cfg", %keymapperPath% ; Load HyperSpin profile
	}Else{
		DetectHiddenWindows, On
		WinClose, JoyToKey ahk_class TMainForm ; or close if HyperSpin profile doesn't exist
	}
}
}

Log(text,state="") {
FormatTime, logTime,, hh:mm:ss tt |%A_Space%%A_Space%
Global logFile
If state
	FileAppend, %text%`n, %logFile%
Else
	FileAppend, %logTime%%text%`n, %logFile%
}

IniReadCheck(file,section,key,defaultvalue="") {
IniRead, inivar, %file%, %section%, %key%
If ( inivar = "ERROR" ) {
	IniWrite, %defaultvalue%, %file%, %section%, %key%
	Return defaultvalue
}
Return iniVar
}

CreateGlobalFile: ; ********REMOVE THIS ONCE HS2 IS OUT****************
iniMigrate =
( ltrim c
   HyperLaunch, Hide_Cursor, false
   HyperLaunch, Fade_In, false
   HyperLaunch, Fade_Out, false
   HyperLaunch, Fade_Color, 0x000000
   HyperLaunch, Fade_In_Duration, 500
   HyperLaunch, Fade_Out_Duration, 500
   HyperLaunch, Fade_In_Delay, 0
   HyperLaunch, Keymapper_Enabled, false
   HyperLaunch, Keymapper, %A_Space%
)
Loop, Parse, iniMigrate, `n
{
	StringSplit, split, A_LoopField, `,, %A_Space%%A_Tab%
	IniRead, tempVar, %settingsFile%, %split1%, %split2%
	If % tempVar!="ERROR" ; if user has this setting, let's write it to the global ini
		IniWrite, % tempVar, %globalFile%, %split1%, %split2%
	If % tempVar="ERROR" ; if user never set this this setting, let's write the default to the global ini
		IniWrite, % split3, %globalFile%, %split1%, %split2%
}
Return


ToggleCursor:
SystemCursor("Toggle")
Return

GuiClose:
ExitScript()

ExitScript:
Log("User pressed exit_script_key")
ExitScript()
Return 

ExitScript() {
Global keymapperEnabled
Global hideTaskbar
If (hideTaskbar = "true"){
	Log("Unhiding taskbar")
	WinShow, ahk_class Shell_TrayWnd
	WinShow, ahk_class Button
}
If (keymapperEnabled = "true" )
	UnloadKeyMapper()
Process, Exist, HyperSpin.exe
PID := errorLevel
If (PID) {
	WinActivate, ahk_pid %PID%
	WinWaitActive, ahk_pid %PID%
}
SendMessage,0x112,0xF170,-1,,Program Manager
SystemCursor("On")
;Emergency restore cursor, just in case something goes wrong
SPI_SETCURSORS := 0x57
DllCall( "SystemParametersInfo", UInt,SPI_SETCURSORS, UInt,0, UInt,0, UInt,0 )
Log("

","end")

ExitApp

}

[/code]

Edit:

I think I have a lead.

Posted

I'VE GOT IT!

I HAVE IT... IT WORKS... :-D yahoo

that damn -ad command was not needed and throwing me off after I got the rest squared away.

Here is the final revision to what was changed,

;-----------------------------------------------------------------------------------------------------------------------------------------
; HyperLaunch V2.25c
; By BBB & djvj
; This can only be compiled with Authotkey_H
; http://www.autohotkey.com/forum/topic43049.html
; Replace your normal autohotkey.exe with the one from autohotkey_h
; Requires autohotkey.dll
; Must reside in HS install directory
;
; Added unrar.exe support by tastyratz
;
;
;-----------------------------------------------------------------------------------------------------------------------------------------

#NoTrayIcon
#SingleInstance Ignore
#InstallKeybdHook
SetTitleMatchMode 2
DetectHiddenWindows, ON
SetWorkingDir % A_ScriptDir
logFile = %A_ScriptDir%\HyperLaunch.log
Version = 2.25d
forHS2 = false	; remove when HS2 released
#Include %A_ScriptDir%\Gdip.ahk
;-----------------------------------------------------------------------------------------------------------------------------------------
;-----------------------------------------------------------------------------------------------------------------------------------------
; Gui
;-----------------------------------------------------------------------------------------------------------------------------------------
;-----------------------------------------------------------------------------------------------------------------------------------------
;Read last system and last rom so we dont have to fill it in for testing
settingsFile := checkFile(A_ScriptDir . "\Settings\Settings.ini")
; globalFile := checkFile(A_ScriptDir . "\Settings\Global Settings.ini") ; UNCOMMENT WHEN HS2 COMES OUT
globalFile := A_ScriptDir . "\Settings\Global Settings.ini" ; REMOVE WHEN HS2 COMES OUT, not everyone will have this file yet
IfNotExist, %globalFile%
GoSub, CreateGlobalFile

lastSystem := IniReadCheck(settingsFile, "HyperLaunch", "Last_System")
lastRom := IniReadCheck(settingsFile, "HyperLaunch", "Last_Rom")

hideCursorGlobal := IniReadCheck(globalFile, "HyperLaunch", "Hide_Cursor", "false") ; hide cursor, only used for gui launching
If (hideCursorGlobal = "true"){
hideCursorChecked = 1
}Else{
hideCursorChecked = 0
}
hideDesktopGlobal := IniReadCheck(globalFile, "HyperLaunch", "Hide_Desktop", "false")
If (hideDesktopGlobal = "true"){
hideDesktopChecked = 1
}Else{
hideDesktopChecked = 0
}
hideTaskbarGlobal := IniReadCheck(globalFile, "HyperLaunch", "Hide_Taskbar", "false")
If (hideTaskbarGlobal = "true"){
hideTaskbarChecked = 1
}Else{
hideTaskbarChecked = 0
}   

;-----------------------------------------------------------------------------------------------------------------------------------------
; Starting Log
;-----------------------------------------------------------------------------------------------------------------------------------------
FileDelete, %logFile%
Log("[code]","start")
Log("HyperLaunch v" . Version)
WinGetPos,,, hsW, hsH, HyperSpin,, Notepad
isAdmin:=(If A_IsAdmin=1 ? ("Yes") : ("No"))
logTxt := "System Specs:`n`t`tHyperSpin Dir: " . A_ScriptDir . "`n`t`tOS: " . A_OSVersion . "`n`t`tOS Language: " . A_Language . "`n`t`tOS Admin Status: " . isAdmin:=(If A_IsAdmin=1 ? ("Yes") : ("No"))
SysGet, MonitorCount, MonitorCount, SysGet, MonitorPrimary, MonitorPrimary
Loop, %MonitorCount% ; get each monitor's stats for the log
{
SysGet, MonitorName, MonitorName, %A_Index%
SysGet, Monitor, Monitor, %A_Index%
SysGet, MonitorWorkArea, MonitorWorkArea, %A_Index%
logTxt .= "`n`t`tMonitor #" . A_Index . (If MonitorPrimary = A_Index ? (" (Primary)"):("")) . " (" . MonitorName . "): " . MonitorRight . "x" . MonitorBottom . " (" . MonitorWorkAreaRight . "x" . MonitorWorkAreaBottom . " work)"
}
logTxt .= "`n`t`tHyperSpin Res: " . hsW . "x" . hsH . "`n`t`tAHK Version: " . A_AhkVersion
Log(logTxt)
; HyperSpin_2_0
; ahk_class ApolloRuntimeContentWindow
; HyperSpin
; ahk_class ThunderRT6FormDC

If 0 < 2
{
;Read system xml to optionally fill in the first combo
Hotkey, ~Enter, Button1
getSystems()
Gui, Add, Text, x12 y10 w430 h20 , Command Line: HyperLaunch.exe SystemName RomName
Gui, Add, Text, x12 y40 w360 h30 , You can run a test below by entering the system name and rom name below then clicking the Test button.
Gui, Add, Edit, x12 y150 w266 h20 vEdit2, %lastRom%
Gui, Add, Text, x12 y80 w80 h20 , System Name:
Gui, Add, Text, x12 y130 w140 h20 , Rom Name(no extension):
Gui, Add, Button, x312 y100 w60 h70 gButton1, Test
Gui, Add, Button, x262 y180 w110 h40 gButton2, Download Modules
Gui, Add, Button, x279 y150 w24 h20 gButton3, .
Gui, Add, Button, x279 y100 w24 h20 gButton4, .
Gui, Add, Checkbox, x12 y180 w130 h20 vCheck1, Debug Module Script
Gui, Add, CheckBox, x12 y200 w130 h20 Checked%hideCursorChecked% vChecked2 gCheck2, Hide Cursor
Gui, Add, CheckBox, x142 y180 w110 h20 Checked%hideDesktopChecked% vChecked3 gCheck3, Hide Desktop
Gui, Add, CheckBox, x142 y200 w110 h20 Checked%hideTaskbarChecked% vChecked4 gCheck4, Hide Taskbar
Gui, Show, Center h233 w386, HyperLaunch %Version%

Log("HyperLaunch launched directly")
Return
}Else{
systemName = %1%
romName = %2%
; Blocking enter to avoid duplicate HyperLaunch launches
; Hotkey, Enter, BlockKeyInput
; Hotkey, 1, BlockKeyInput
Goto, Start
Return
}

Check2:
Gui, Submit , NoHide
If (Checked2 = 0){
	IniWrite, false, %globalFile%, HyperLaunch, Hide_Cursor
}Else{
	IniWrite, true, %globalFile%, HyperLaunch, Hide_Cursor
}
IniRead, hideCursor, %globalFile%, HyperLaunch, Hide_Cursor, false
Return

Check3:
Gui, Submit , NoHide
If (Checked3 = 0){
	IniWrite, false, %globalFile%, HyperLaunch, Hide_Desktop
}Else{
	IniWrite, true, %globalFile%, HyperLaunch, Hide_Desktop
}  
IniRead, hideDesktop, %globalFile%, HyperLaunch, Hide_Desktop, false 
Return

Check4:
Gui, Submit , NoHide
If (Checked4 = 0){
	IniWrite, false, %globalFile%, HyperLaunch, Hide_Taskbar
}Else{
	IniWrite, true, %globalFile%, HyperLaunch, Hide_Taskbar
}  
IniRead, hideTaskbar, %globalFile%, HyperLaunch, Hide_Taskbar, false
Return

Button3:
;File browser
;Try and get the users rompath to start in
Gui, Submit, NoHide
If forHS2 = true
	IniRead, startDir, %A_ScriptDir%\Settings\%Edit1%.ini, Exe Info, Rom_Path, %A_ScriptDir%
Else
	IniRead, startDir, %A_ScriptDir%\Settings\%Edit1%.ini, Exe Info, Rompath, %A_ScriptDir%
startDir := GetFullName(startDir)
StringRight, lastChar, startDir, 1
If (lastChar = "\"){
	StringTrimRight, startDir, startDir, 1 
}
FileSelectFile, SelectedFile, 3, %startDir%, Select a rom,
If SelectedFile =
	Return
Else
	RegExMatch(SelectedFile,  "\\([^\\]*)\.\w{2,3}$", SubPat) 
GuiControl,, Edit2, %SubPat1%
Return

Button4:
;Opens new gui to configure an emu
Gui, Submit , NoHide 
Gui, 3:+owner1
Gui +Disabled
configFile := checkFile(A_ScriptDir . "\Settings\" . Edit1 . ".ini")
IniRead, configExePath, %configFile%, Exe Info, Path,
StringRight, lastChar, configExePath, 1
If (lastChar != "\"){
	configExePath += "\"
}

IniRead, configExe, %configFile%, Exe Info, Exe
If forHS2 = true
	IniRead, configRomPath, %configFile%, Exe Info, Rom_Path
Else
	IniRead, configRomPath, %configFile%, Exe Info, Rompath
IniRead, configRomExtension, %configFile%, Exe Info, Romextension
configPerGameModules := IniReadCheck(configFile, "Exe Info", "Per_Game_Modules", "false")
configCPWizardEnabled := IniReadCheck(configFile, "Exe Info", "Cp_Wizard_Enabled", "use_global")

finalPath = %configExePath%%configExe%
If (finalPath = 0){
	finalPath := ""
}

Gui, 3:Add, Text, x12 y10 w210 h20 , Emulator:
Gui, 3:Add, Text, x12 y60 w210 h20 , Rom Path:
Gui, 3:Add, Text, x12 y110 w210 h20 , Rom Extension:
Gui, 3:Add, Edit, x12 y30 w330 h20 v3Edit1 g3Edit1, %finalPath%
Gui, 3:Add, Edit, x12 y80 w330 h20 v3Edit2 g3Edit2, %configRomPath%
Gui, 3:Add, Edit, x12 y130 w330 h20 v3Edit3 g3Edit3, %configRomExtension% 
Gui, 3:Add, Button, x342 y30 w20 h20 g3Button1, .
Gui, 3:Add, Button, x342 y80 w20 h20 g3Button2, .

If (configPerGameModules = "true"){
	configPerGameModulesChecked = 1
}Else{
	configPerGameModulesChecked = 0
} 

If (configCPWizardEnabled = "true"){
	configCPWizardEnabledChecked = 1
}Else{
	configCPWizardEnabledChecked = 0
}  

Gui, 3:Add, CheckBox, x12 y160 w120 h20 Checked%configPerGameModulesChecked% v3Checked1 g3Check1, Per Game Modules
Gui, 3:Add, CheckBox, x142 y160 w100 h20 Checked%configCPWizardEnabledChecked% v3Checked2 g3Check2, Enable CPWizard
Gui, 3:Show, x550 y301 h211 w372, Quick Config
Return

3GuiClose:
Gui, 1:-Disabled
Gui, 3:Destroy
Return

3Edit1:
Gui, 3:Submit, NoHide
RegExMatch(3Edit1,  "(.*\\)([^\\]*\.\w{2,3})$", SubPat)
IniWrite, %SubPat1%, %configFile%, Exe Info, Path
IniWrite, %SubPat2%, %configFile%, Exe Info, Exe
Return

3Edit2:
Gui, 3:Submit, NoHide
If forHS2 = true
	IniWrite, %3Edit2%, %configFile%, Exe Info, Rom_Path
Else
	IniWrite, %3Edit2%, %configFile%, Exe Info, Rompath
Return

3Edit3:
Gui, 3:Submit , NoHide
IniWrite, %3Edit3%, %configFile%, Exe Info, Romextension
Return

3Check1:
Gui, 3:Submit , NoHide
If (3Checked1 = 0){
	IniWrite, false, %configFile%, Exe Info, Per_Game_Modules
}Else{
	IniWrite, true, %configFile%, Exe Info, Per_Game_Modules
}
Return

3Check2:
Gui, 3:Submit , NoHide
If (3Checked2 = 0){
	IniWrite, false, %configFile%, Exe Info, Cp_Wizard_Enabled
}Else{
	IniWrite, true, %configFile%, Exe Info, Cp_Wizard_Enabled
}
Return

Button2:
Run, http://hyperlist.hyperspin-fe.com/?module=browseahk
Return

Button1:
IfWinActive, HyperLaunch
{
	Gui, Submit , NoHide
	Hotkey, ~Enter, Off
	systemName = %Edit1%																													  
	romName = %Edit2%
	debugModule = %Check1%
	Goto, Start
}
Return

3Button1:
Gui, 3:Submit, NoHide
FileSelectFile, SelectedFile, 3, %3Edit1%, Select Executable,
If SelectedFile =
	Return
Else
	RegExMatch(SelectedFile,  "(.*\\)([^\\]*\.\w{3,3})$", SubPat)
IniWrite, %SubPat1%, %configFile%, Exe Info, Path
IniWrite, %SubPat2%, %configFile%, Exe Info, Exe
GuiControl,, 3Edit1, %SubPat1%%SubPat2%
Return

3Button2:
Gui, 3:Submit, NoHide
StringRight, lastChar, 3Edit2, 1
If (lastChar = "\"){
	StringTrimRight, startDir, 3Edit2, 1
}
FileSelectFolder, selectedFolder, *%startDir%, Select RomPath,
If selectedFolder =
	Return
Else
	StringRight, lastChar, selectedFolder, 1
If (lastChar != "\"){
	selectedFolder = %selectedFolder%\
}

If forHS2 = true
	IniWrite, %selectedFolder%, %configFile%, Exe Info, Rom_Path
Else
	IniWrite, %selectedFolder%, %configFile%, Exe Info, Rompath
GuiControl,, 3Edit2, %selectedFolder%
Return

BlockKeyInput:
Sleep, 2500
Hotkey, Enter, off
Hotkey, 1, off
Return

Start:
Gui Destroy
IniWrite, %systemName%, %settingsFile%, HyperLaunch, Last_System
IniWrite, %romName%, %settingsFile%, HyperLaunch, Last_Rom

Log("HyperLaunch received """ . systemName . """ and """ . romName . """")

;-----------------------------------------------------------------------------------------------------------------------------------------
;-----------------------------------------------------------------------------------------------------------------------------------------
; Get Ini Settings
;-----------------------------------------------------------------------------------------------------------------------------------------
;-----------------------------------------------------------------------------------------------------------------------------------------
; In HS2, if using PCLauncher, your systemName will be PCLauncher, instead of your wheel's name
If (systemName = "Main Menu")
iniName = %romName%
Else ;If (systemName != "PCLauncher") ; Probably don't want this "If" check anymore because PCLauncher needs an ini so it can check for fade functionality
iniName = %systemName%


; If (systemName != "PCLauncher") ; Same as above comment, need to check for an ini from now on
iniFile := checkFile(A_ScriptDir . "\Settings\" . iniName . ".ini")

;-----------------------------------------------------------------------------------------------------------------------------------------
; Main Settings from Settings\Settings.ini
;-----------------------------------------------------------------------------------------------------------------------------------------
exitScriptKey := IniReadCheck(settingsFile, "HyperLaunch", "Exit_Script_Key", "~q & ~s")
exitEmulatorKey := IniReadCheck(settingsFile, "HyperLaunch", "Exit_Emulator_Key", "Esc")
toggleCursorKey := IniReadCheck(settingsFile, "HyperLaunch", "Toggle_Cursor_Key", "t")
mgKey := IniReadCheck(settingsFile, "HyperLaunch", "MultiGame_Key", "NumpadSub")
mgSelectKey := IniReadCheck(settingsFile, "HyperLaunch", "MultiGame_Select_Key", "Enter")
mgExitKey := IniReadCheck(settingsFile, "HyperLaunch", "MultiGame_Exit_Key", "Esc")
daemonToolsPath := IniReadCheck(settingsFile, "HyperLaunch", "Path_To_Daemontools")
daemonToolsPath := GetFullName(daemonToolsPath)
cpWizardPath := IniReadCheck(settingsFile, "HyperLaunch", "Path_To_CPWizard")
cpWizardPath := GetFullName(cpWizardPath)

fadeInInterruptKeys := IniReadCheck(settingsFile, "HyperLaunch", "Fade_In_Interrupt_Keys", "anykey")

keymapperFullPath := IniReadCheck(settingsFile, "HyperLaunch", "Keymapper_Path", A_Space)
keymapperProfilePath := IniReadCheck(settingsFile, "HyperLaunch", "Keymapper_Profiles_Path", A_ScriptDir . "\Keymapper Profiles\")
IfInString, keymapperProfilePath, `%A_ScriptDir`% ; replacing default value if it exists with user's actual HS path
{
StringReplace, keymapperProfilePath, keymapperProfilePath, `%A_ScriptDir`%, %A_ScriptDir%
IniWrite, %keymapperProfilePath%, %settingsFile%, HyperLaunch, Keymapper_Profiles_Path
}

;-----------------------------------------------------------------------------------------------------------------------------------------
; Global Settings from Settings\Global Settings.ini
;-----------------------------------------------------------------------------------------------------------------------------------------
cpWizardEnabledGlobal := IniReadCheck(globalFile, "HyperLaunch", "CPWizard_Enabled", "false")
cpWizardDelayGlobal := IniReadCheck(globalFile, "HyperLaunch", "CPWizard_Delay", 8000)
cpWizardParamsGlobal := IniReadCheck(globalFile, "HyperLaunch", "CPWizard_Params", "-minimized -timeout 9000")

fadeInGlobal := IniReadCheck(globalFile, "HyperLaunch", "Fade_In", "false")
fadeOutGlobal := IniReadCheck(globalFile, "HyperLaunch", "Fade_Out", "false")
fadeColorGlobal := IniReadCheck(globalFile, "HyperLaunch", "Fade_Color", "0x000000")
fadeInDurationGlobal := IniReadCheck(globalFile, "HyperLaunch", "Fade_In_Duration", "500")
fadeOutDurationGlobal := IniReadCheck(globalFile, "HyperLaunch", "Fade_Out_Duration", "500")
fadeInDelayGlobal := IniReadCheck(globalFile, "HyperLaunch", "Fade_In_Delay", "0")

7zEnableGlobal := IniReadCheck(globalFile, "HyperLaunch", "7z_Enabled", "false")
7zExtractDirFromIniGlobal := IniReadCheck(globalFile, "HyperLaunch", "7z_Extract_Dir", A_Temp . "\Hyperspin\")
7zDelTempGlobal := IniReadCheck(globalFile, "HyperLaunch", "7z_Delete_Temp", "true")

;Added by Tastyratz for Winrar support +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+----------
rarEnableGlobal := IniReadCheck(globalFile, "HyperLaunch", "rar_Enabled", "false")
rarExtractDirFromIniGlobal := IniReadCheck(globalFile, "HyperLaunch", "rar_Extract_Dir", A_Temp . "\Hyperspin\")
rarDelTempGlobal := IniReadCheck(globalFile, "HyperLaunch", "rar_Delete_Temp", "true")


keymapperEnabledGlobal := IniReadCheck(globalFile, "HyperLaunch", "Keymapper_Enabled", "false")
keymapperGlobal := IniReadCheck(globalFile, "HyperLaunch", "Keymapper", A_Space)

mgEnabledGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Enabled", "false")
mgBackgroundColorGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Background_Color", "FF000000")
mgSidePaddingGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Side_Padding", "0.2")
mgYOffsetGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Y_Offset", "500")
mgImageAdjustGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Image_Adjust", "1")
mgFontGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Font", "Arial")
mgText1OptionsGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Text_1_Options", "x10p y30p w80p Centre cBBFFFFFF r4 s100 Bold Italic")
mgText1TextGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Text_1_Text", "Please select a game")
mgText2OptionsGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Text_2_Options", "w96p cFFFFFFFF r4 s50 Center Bold Italic")
mgText2OffsetGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Text_2_Offset", "70")
mgUseSoundGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Use_Sound", "true")
mgSoundfreqGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Sound_Frequency", "300")
mgExitEffectGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Exit_Effect", "none")
mgSelectedEffectGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Selected_Effect", "rotate")
mgUseGameArtGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Use_Game_Art", "false")
mgArtworkDirGlobal := IniReadCheck(globalFile, "HyperLaunch", "MultiGame_Art_Folder", "Artwork1")

;-----------------------------------------------------------------------------------------------------------------------------------------
; System Specific Settings from systemName.ini
;-----------------------------------------------------------------------------------------------------------------------------------------
IniRead, emuPath, %iniFile%, Exe Info, Path
emuPath := GetFullName(emuPath)
If forHS2 = true
IniRead, romPathFromIni, %iniFile%, Exe Info, Rom_Path
Else
IniRead, romPathFromIni, %iniFile%, Exe Info, Rompath
romPath := GetFullName(romPathFromIni)
IniRead, executable, %iniFile%, Exe Info, Exe
IniRead, romExtensions, %iniFile%, Exe Info, Romextension

perGameModules := IniReadCheck(iniFile, "Exe Info", "Per_Game_Modules", "false")
skipChecks := IniReadCheck(iniFile, "Exe Info", "Skipchecks", "false")

hideCursorSystem := IniReadCheck(iniFile, "Exe Info", "Hide_Cursor", "use_global")
hideDesktopSystem := IniReadCheck(iniFile, "Exe Info", "Hide_Desktop", "use_global")
hideTaskbarSystem := IniReadCheck(iniFile, "Exe Info", "Hide_Taskbar", "use_global")

cpWizardEnabledSystem := IniReadCheck(iniFile, "Exe Info", "CPWizard_Enabled", "use_global")
cpWizardDelaySystem := IniReadCheck(iniFile, "Exe Info", "CPWizard_Delay", "use_global")
cpWizardParamsSystem := IniReadCheck(iniFile, "Exe Info", "CPWizard_Params", "use_global")

fadeInSystem := IniReadCheck(iniFile, "Exe Info", "Fade_In", "use_global")
fadeOutSystem := IniReadCheck(iniFile, "Exe Info", "Fade_Out", "use_global")
fadeColorSystem := IniReadCheck(iniFile, "Exe Info", "Fade_Color", "use_global")
fadeInDurationSystem := IniReadCheck(iniFile, "Exe Info", "Fade_In_Duration", "use_global")
fadeOutDurationSystem := IniReadCheck(iniFile, "Exe Info", "Fade_Out_Duration", "use_global")
fadeInDelaySystem := IniReadCheck(iniFile, "Exe Info", "Fade_In_Delay", "use_global")

7zEnableSystem := IniReadCheck(iniFile, "Exe Info", "7z_Enabled", "use_global")
7zExtractDirFromIniSystem := IniReadCheck(iniFile, "Exe Info", "7z_Extract_Dir", "use_global")
7zDelTempSystem := IniReadCheck(iniFile, "Exe Info", "7z_Delete_Temp", "use_global")

;Added by Tastyratz for Winrar support +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+----------
rarEnableSystem := IniReadCheck(iniFile, "Exe Info", "rar_Enabled", "use_global")
rarExtractDirFromIniSystem := IniReadCheck(iniFile, "Exe Info", "rar_Extract_Dir", "use_global")
rarDelTempSystem := IniReadCheck(iniFile, "Exe Info", "rar_Delete_Temp", "use_global")

keymapperEnabledSystem := IniReadCheck(iniFile, "Exe Info", "Keymapper_Enabled", "use_global") ; per system enable key
keymapperSystem := IniReadCheck(iniFile, "Exe Info", "Keymapper", "use_global") ; per system keymapper

mgEnabledSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Enabled", "use_global")
mgBackgroundColorSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Background_Color", "use_global")
mgSidePaddingSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Side_Padding", "use_global")
mgYOffsetSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Y_Offset", "use_global")
mgImageAdjustSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Image_Adjust", "use_global")
mgFontSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Font", "use_global")
mgText1OptionsSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Text_1_Options", "use_global")
mgText1TextSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Text_1_Text", "use_global")
mgText2OptionsSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Text_2_Options", "use_global")
mgText2OffsetSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Text_2_Offset", "use_global")
mgUseSoundSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Use_Sound", "use_global")
mgSoundfreqSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Sound_Frequency", "use_global")
mgExitEffectSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Exit_Effect", "use_global")
mgSelectedEffectSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Selected_Effect", "use_global")
mgUseGameArtSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Use_Game_Art", "use_global")
mgArtworkDirSystem := IniReadCheck(iniFile, "Exe Info", "MultiGame_Art_Folder", "use_global")

;-----------------------------------------------------------------------------------------------------------------------------------------
; Converting Global/System variables for use later
;-----------------------------------------------------------------------------------------------------------------------------------------
hideCursor := (If hideCursorSystem = "use_global" ? (hideCursorGlobal) : (hideCursorSystem))
hideDesktop := (If hideDesktopSystem = "use_global" ? (hideDesktopGlobal) : (hideDesktopSystem))
hideTaskbar := (If hideTaskbarSystem = "use_global" ? (hideTaskbarGlobal) : (hideTaskbarSystem))

cpWizardEnabled := (If cpWizardEnabledSystem= "use_global" ? (cpWizardEnabledGlobal) : (cpWizardEnabledSystem))
cpWizardDelay := (If cpWizardDelaySystem= "use_global" ? (cpWizardParamsGlobal) : (cpWizardDelaySystem))
cpWizardParams := (If cpWizardParamsSystem= "use_global" ? (cpWizardParamsGlobal) : (cpWizardParamsSystem))

keymapperEnabled := (If keymapperEnabledSystem= "use_global" ? (keymapperEnabledGlobal) : (keymapperEnabledSystem))
keymapper := (If keymapperSystem = "use_global" ? (keymapperGlobal) : (keymapperSystem))

fadeIn := (If fadeInSystem = "use_global" ? (fadeInGlobal) : (fadeInSystem))
fadeInDuration := (If fadeInDurationSystem = "use_global" ? (fadeInDurationGlobal) : (fadeInDurationSystem))
fadeInDelay := (If fadeInDelaySystem = "use_global" ? (fadeInDelayGlobal) : (fadeInDelaySystem))
fadeColor := (If fadeColorSystem = "use_global" ? (fadeColorGlobal) : (fadeColorSystem))
fadeOut := (If fadeOutSystem = "use_global" ? (fadeOutGlobal) : (fadeOutSystem))
fadeOutDuration := (If fadeOutDurationSystem = "use_global" ? (fadeOutDurationGlobal) : (fadeOutDurationSystem))

7zEnable := (If (7zEnableSystem = "use_global") ? (7zEnableGlobal) : (7zEnableSystem))
7zExtractDirFromIni := (If (7zExtractDirFromIniSystem = "use_global") ? (7zExtractDirFromIniGlobal) : (7zExtractDirFromIniSystem))
7zDelTemp := (If (7zDelTempSystem = "use_global") ? (7zDelTempGlobal) : (7zDelTempSystem))
7zExtractDir := 7zExtractDirFromIni

;Added by Tastyratz for Winrar support +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+----------
rarEnable := (If (rarEnableSystem = "use_global") ? (rarEnableGlobal) : (rarEnableSystem))
rarExtractDirFromIni := (If (rarExtractDirFromIniSystem = "use_global") ? (rarExtractDirFromIniGlobal) : (rarExtractDirFromIniSystem))
DelTemp := (If (rarDelTempSystem = "use_global") ? (rarDelTempGlobal) : (rarDelTempSystem))
rarExtractDir := rarExtractDirFromIni



mgEnabled := (If (mgEnabledSystem = "use_global") ? (mgEnabledGlobal) : (mgEnabledSystem))
mgBackgroundColor := (If (mgBackgroundColorSystem = "use_global") ? (mgBackgroundColorGlobal) : (mgBackgroundColorSystem))
mgSidePadding := (If (mgSidePaddingSystem = "use_global") ? (mgSidePaddingGlobal) : (mgSidePaddingSystem))
mgYOffset := (If (mgYOffsetSystem = "use_global") ? (mgYOffsetGlobal) : (mgYOffsetSystem))
mgImageAdjust := (If (mgImageAdjustSystem = "use_global") ? (mgImageAdjustGlobal) : (mgImageAdjustSystem))
mgFont := (If (mgFontSystem = "use_global") ? (mgFontGlobal) : (mgFontSystem))
mgText1Options := (If (mgText1OptionsSystem = "use_global") ? (mgText1OptionsGlobal) : (mgText1OptionsSystem))
mgText1Text := (If (mgText1TextSystem = "use_global") ? (mgText1TextGlobal) : (mgText1TextSystem))
mgText2Options := (If (mgText2OptionsSystem = "use_global") ? (mgText2OptionsGlobal) : (mgText2OptionsSystem))
mgText2Offset := (If (mgText2OffsetSystem = "use_global") ? (mgText2OffsetGlobal) : (mgText2OffsetSystem))
mgUseSound := (If (mgUseSoundSystem = "use_global") ? (mgUseSoundGlobal) : (mgUseSoundSystem))
mgSoundfreq := (If (mgSoundfreqSystem = "use_global") ? (mgSoundfreqGlobal) : (mgSoundfreqSystem))
mgExitEffect := (If (mgExitEffectSystem = "use_global") ? (mgExitEffectGlobal) : (mgExitEffectSystem))
mgSelectedEffect := (If (mgSelectedEffectSystem = "use_global") ? (mgSelectedEffectGlobal) : (mgSelectedEffectSystem))
mgUseGameArt := (If (mgUseGameArtSystem = "use_global") ? (mgUseGameArtGlobal) : (mgUseGameArtSystem))
mgArtworkDir := (If (mgArtworkDirSystem = "use_global") ? (mgArtworkDirGlobal) : (mgArtworkDirSystem))

; msgbox, iniFile=%iniFile%`nsettingsFile=%settingsFile%`nglobalFile=%globalFile%`n`nSettings.ini`n`nexitScriptKey=%exitScriptKey%`nexitEmulatorKey=%exitEmulatorKey%`ntoggleCursorKey=%toggleCursorKey%`ndaemonToolsPath=%daemonToolsPath%`ncpWizardPath=%cpWizardPath%`ncpWizardDelay=%cpWizardDelay%`ncpWizardParams=%cpWizardParams%`nfadeInInterruptKeys=%fadeInInterruptKeys%`nkeymapperFullPath=%keymapperFullPath%`nkeymapperProfilePath=%keymapperProfilePath%`n`nGlobal Settings.ini`n`nfadeInGlobal=%fadeInGlobal%`nfadeOutGlobal=%fadeOutGlobal%`nfadeColorGlobal=%fadeColorGlobal%`nfadeInDurationGlobal=%fadeInDurationGlobal%`nfadeOutDurationGlobal=%fadeOutDurationGlobal%`nfadeInDelayGlobal=%fadeInDelayGlobal%`nkeymapperEnabledGlobal=%keymapperEnabledGlobal%`nkeymapperGlobal=%keymapperGlobal%`nmgBackgroundColorGlobal=%mgBackgroundColorGlobal%`nmgYOffsetGlobal=%mgYOffsetGlobal%`nmgImageAdjustGlobal=%mgImageAdjustGlobal%`nmgFontGlobal=%mgFontGlobal%`nmgText1OptionsGlobal=%mgText1OptionsGlobal%`nmgText1TextGlobal=%mgText1TextGlobal%`nmgText2OptionsGlobal=%mgText2OptionsGlobal%`nmgText2OffsetGlobal=%mgText2OffsetGlobal%`nmgUseSoundGlobal=%mgUseSoundGlobal%`nmgSoundfreqGlobal=%mgSoundfreqGlobal%`nmgExitEffectGlobal=%mgExitEffectGlobal%`n`n%systemName%.ini`n`nemuPath=%emuPath%`nromPath=%romPath%`nexecutable=%executable%`nromExtensions=%romExtensions%`nskipchecks=%skipchecks%`nperGameModules=%perGameModules%`ncpWizardEnabled=%cpWizardEnabled%`nfadeInSystem=%fadeInSystem%`nfadeOutSystem=%fadeOutSystem%`nfadeColorSystem=%fadeColorSystem%`nfadeInDurationSystem=%fadeInDurationSystem%`nfadeOutDurationSystem=%fadeOutDurationSystem%`nfadeInDelaySystem=%fadeInDelaySystem%`n7zEnable=%7zEnable%`n7zExtractDir=%7zExtractDir%`n7zDelTemp=%7zDelTemp%`nrarEnable=%rarEnable%`nrarExtractDir=%rarExtractDir%`nrarDelTemp=%rarDelTemp%`nkeymapperEnabledSystem=%keymapperEnabledSystem%`nkeymapperSystem=%keymapperSystem%`nmgEnabled=%mgEnabled%`nmgBackgroundColorSystem=%mgBackgroundColorSystem%`nmgYOffsetSystem=%mgYOffsetSystem%`nmgImageAdjustSystem=%mgImageAdjustSystem%`nmgFontSystem=%mgFontSystem%`nmgText1OptionsSystem=%mgText1OptionsSystem%`nmgText1TextSystem=%mgText1TextSystem%`nmgText2OptionsSystem=%mgText2OptionsSystem%`nmgText2OffsetSystem=%mgText2OffsetSystem%`nmgUseSoundSystem=%mgUseSoundSystem%`nmgSoundfreqSystem=%mgSoundfreqSystem%`nmgExitEffectSystem=%mgExitEffectSystem%

Log("INI Keys read")

;-----------------------------------------------------------------------------------------------------------------------------------------

; Check if emu is already running and/or cancel duplicate HyperLaunch launches. This is disabled for PCLauncher because %executable% is always blank, which causes ErrorLevel to not be 0.
If (systemName != "PCLauncher"){ ; This "If" is only for HS2, HS1 does not use PCLauncher as a systemName, so this "If" will always be true
Process, Exist, %executable%
If (ErrorLevel != 0) {
	Log("Possible duplicate launch. " . executable . " is already running, closing HyperLaunch")
	ExitApp
}
}

; Removes spaces from romExtensions if user accidentally placed them
StringReplace, romExtensions, romExtensions, %A_Space%,, All

;Verify settings
If (systemName != "PCLauncher" && skipChecks != "true"){
romExtension := checkPaths()
} Else If (skipChecks = "true") {
Log("skipChecks is enabled")
romExtension := GetExtensions() ; This is so we can still get our romExtension if we have skipchecks set to true for systems like scummvm and dosbox that do not contain a romName inside an archive
}
romExtensionOrig := romExtension ; Storing original romExtension in case 7z support is used, we lose original extension of the rom after processing through the 7z function. This is used when 7z and MultiGame support are used together.

; Convert fadeInInterruptKeys variable to cover all keys if user has it set for anykey
If (fadeInInterruptKeys = "anykey")
fadeInInterruptKeys = {LControl}{RControl}{LAlt}{RAlt}{LShift}{RShift}{LWin}{RWin}{AppsKey}{F1}{F2}{F3}{F4}{F5}{F6}{F7}{F8}{F9}{F10}{F11}{F12}{Left}{Right}{Up}{Down}{Home}{End}{PgUp}{PgDn}{Del}{Ins}{BS}{Capslock}{Numlock}{PrintScreen}{Pause}

;-----------------------------------------------------------------------------------------------------------------------------------------
; Build new script with module
; We'll use ahktextdll instead of ahkdll to add our own stuff to the script
; This will keep the modules more simplified
;-----------------------------------------------------------------------------------------------------------------------------------------
MScript := buildScript()
Log("Module is built")

;-----------------------------------------------------------------------------------------------------------------------------------------
; Load DLL
;-----------------------------------------------------------------------------------------------------------------------------------------
AhkDll := checkFile(A_ScriptDir . "\AutoHotkey.dll")
DllCall("LoadLibrary","Str",AhkDll)

;-----------------------------------------------------------------------------------------------------------------------------------------
;-----------------------------------------------------------------------------------------------------------------------------------------
; Pre Launch
;-----------------------------------------------------------------------------------------------------------------------------------------
;-----------------------------------------------------------------------------------------------------------------------------------------
HotKey, %exitScriptKey%, ExitScript

If (hideTaskbar = "true"){
Log("Hiding taskbar")
WinHide ahk_class Shell_TrayWnd
WinHide, ahk_class Button
}

If ( hideDesktop = "true" && fadeIn != "true" ){
;Were doing a dual hide really, one time for this thread and once for the module
;thread. But this is mainly for if the module writers forget to call it.
Log("Hiding desktop")
Gui, Color, 000000
Gui -Caption +ToolWindow ;+AlwaysOnTop
Gui, Show, x0 y0 W%A_ScreenWidth% H%A_ScreenHeight%, BlackScreen
}

If (hideCursor = "true"){
Log("Hiding mouse cursor")
Hotkey, %toggleCursorKey%, ToggleCursor
SystemCursor("Off")
;Also lets move it to the side since some emu's flash a cursor real quick
;even if we hide it.
CoordMode, Mouse
MouseMove, 0, 0, 0
}

If keymapperEnabled = true
{
	If keymapper not in xpadder,joytokey,ahk
		ScriptError("Your global keymapper is set to """ . keymapperGlobal . """ and this system is set to """ . keymapperSystem . """. Supported choices are xpadder`, joytokey`, or ahk and only one can be used per system",8)
	Log("Loading keymapper -> " . keymapper)
	If ( keymapper != "ahk" )
		CheckFile(keymapperFullPath) ; No need to continue if path set wrong
	SplitPath, keymapperFullPath, keymapperExe, keymapperPath, keymapperExt ; splitting pathname into variables
	hyperspinProfile = %keymapperProfilePath%HyperSpin ; profile while not in an emu and in HyperSpin
	defaultProfile = %keymapperProfilePath%default ; default profile for all systems, loaded when there is no system or rom specific profile
	systemProfile = %keymapperProfilePath%%systemName%\%systemName% ; profile for a specific system, loaded when no rom specific profile is found
	romProfile = %keymapperProfilePath%%systemName%\%romName% ; rom specific profile
	hyperspinProfile := LoadKeyMapper(MScript) ; returning profile in case user needs to load it on module exit
	; msgbox, keymapper variables`nkeymapperExe=%keymapperExe%`nkeymapperExt=%keymapperExt%`nkeymapperPath=%keymapperPath%
}

;-----------------------------------------------------------------------------------------------------------------------------------------
;-----------------------------------------------------------------------------------------------------------------------------------------
; Run Module To Start Launch
;-----------------------------------------------------------------------------------------------------------------------------------------
;-----------------------------------------------------------------------------------------------------------------------------------------

Log("Running module:`n" . MScript)
DllCall(AhkDll "\ahktextdll","Str",MScript,"Str",options,"Str",parameters,"Cdecl UInt")
If (ErrorLevel != 0)
ScriptError("Error running module.")

; The script waits here until the module is finished doing its thing.
While DllCall(AhkDll "\ahkReady")
Sleep, 100
; MsgBox Exiting Main Script

;-----------------------------------------------------------------------------------------------------------------------------------------
;-----------------------------------------------------------------------------------------------------------------------------------------
; Post Launch
;-----------------------------------------------------------------------------------------------------------------------------------------
;-----------------------------------------------------------------------------------------------------------------------------------------
Log("Module ended, exiting HyperLaunch normally")
ExitScript()

;-----------------------------------------------------------------------------------------------------------------------------------------
;-----------------------------------------------------------------------------------------------------------------------------------------
; Functions
;-----------------------------------------------------------------------------------------------------------------------------------------
;-----------------------------------------------------------------------------------------------------------------------------------------
buildScript(){
Static retStr
Static addHideDesktop
Static addFade
Static add7z
Static addrar

Global 0
Global 1
Global 2
Global debugModule
Global perGameModules
Global exitEmulatorKey
Global executable
Global romPath
Global romPathFromIni
Global emuPath
Global romExtension
Global romExtensionOrig
Global romExtensions
Global systemName
Global romName
Global daemonToolsPath
Global skipchecks
Global cpWizardEnabled
Global cpWizardPath
Global cpWizardDelay
Global cpWizardParams
Global hideDesktop
Global fadeIn
Global fadeOut
Global fadeColor
Global fadeInDuration
Global fadeOutDuration
Global fadeInDelay
Global fadeInInterruptKeys
Global 7zEnable
Global 7zExtractDir
Global 7zExtractDirOrig
Global 7zDelTemp
Global rarEnable
Global rarExtractDir
Global rarExtractDirOrig
Global rarDelTemp
Global mgEnabled
Global mgKey
Global mgSelectKey
Global mgExitKey
Global mgBackgroundColor
Global mgSidePadding
Global mgYOffset
Global mgImageAdjust
Global mgFont
Global mgText1Options
Global mgText1Text
Global mgText2Options
Global mgText2Offset
Global mgUseSound
Global mgSoundfreq
Global mgExitEffect
Global mgSelectedEffect
Global mgUseGameArt
Global mgArtworkDir

; Defining the file types we want to support throughout the script
; Some parts we need the period removed, so using 2 vars
7zFormats = .zip,.7z,.gzip,.tar
StringReplace, 7zFormatsNoP, 7zFormats,.,,All

;Added by Tastyratz for Winrar support +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+----------
; Defining the RAR file types we want to support throughout the script
; Some parts we need the period removed, so using 2 vars
rarFormats = .rar
StringReplace, rarFormatsNoP, rarFormats,.,,All

; Defining path for fadeIn Images
gameStartImgPath = %A_ScriptDir%\Media\%systemName%\Images\GameStart\
; Defining path for MultiGame Images
multiGameImgPath = %A_ScriptDir%\Media\%systemName%\Images\MultiGame\
; Defining path for the Module Extension folder
moduleExtensionPath = %A_ScriptDir%\Modules\Module Extensions\

If perGameModules = true
	moduleName := romName
Else
	moduleName := systemName

;Let's run through the module real quick and check for calls to any
;Global functions and add them in manually
moduleFile := checkFile(A_ScriptDir . "\Modules\" . moduleName . "\" . moduleName . ".ahk", "Cannot find: " . A_ScriptDir . "\Modules\" . moduleName . "\" . moduleName . ".ahk" . "`nYou do not have a HyperLaunch 2 module for " . moduleName . ". Please create one or check HyperList.")
Loop, read, %moduleFile%
{
	IfInString, A_LoopReadLine, hideDesktop()
		addHideDesktop := "true"
	IfInString, A_LoopReadLine, DaemonTools(
		addDaemonTools := "true"
}

;Common to all modules
retStr .= "`n;-----------------------------------------------------------"
retStr .= "`n;Built in script"
retStr .= "`n;-----------------------------------------------------------"
retStr .= "`n#NoTrayIcon"
retStr .= "`nDetectHiddenWindows, ON"
retStr .= "`nSetTitleMatchMode`, 2"
 ; required for ahk remapping to work properly with newer dll, might fix other bugs too:
retStr .= "`nSendMode`, Event"

;Common to all modules, inject vars into module
temp0 = %0% ; this is a quick fix for not being able to concenate number on the next line
retStr .= "`n0 = " . temp0
retStr .= "`nexitEmulatorKey = " . exitEmulatorKey
retStr .= "`nemuPath = " . emuPath
retStr .= "`nromPath = " . romPath
retStr .= "`nromPathFromIni = " . romPathFromIni
retStr .= "`nromExtension = " . romExtension
retStr .= "`nromExtensionOrig = " . romExtensionOrig
retStr .= "`nromExtensions = " . romExtensions
retStr .= "`nexecutable = " . executable
retStr .= "`nsystemName = " . systemName
retStr .= "`nromName = " . romName
retStr .= "`ndaemonToolsPath = " . daemonToolsPath
retStr .= "`nskipchecks = " . skipchecks
retStr .= "`nfadeIn = " . fadeIn
retStr .= "`nfadeOut = " . fadeOut
retStr .= "`nfadeColor = " . fadeColor
retStr .= "`nfadeInDuration = " . fadeInDuration
retStr .= "`nfadeOutDuration = " . fadeOutDuration
retStr .= "`nfadeInDelay = " . fadeInDelay
retStr .= "`nfadeInInterruptKeys = " . fadeInInterruptKeys
retStr .= "`ngameStartImgPath = " . gameStartImgPath
retStr .= "`nmoduleExtensionPath = " . moduleExtensionPath
retStr .= "`n7zEnable = " . 7zEnable
retStr .= "`n7zExtractDir = " . 7zExtractDir
retStr .= "`n7zExtractDirOrig = " . 7zExtractDirOrig
retStr .= "`n7zDelTemp = " . 7zDelTemp
retStr .= "`n7zFormats = " . 7zFormats
retStr .= "`n7zFormatsNoP = " . 7zFormatsNoP

;Added by Tastyratz for Winrar support +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+----------
retStr .= "`nrarEnable = " . rarEnable
retStr .= "`nrarExtractDir = " . rarExtractDir
retStr .= "`nrarDelTemp = " . rarDelTemp
retStr .= "`nrarFormats = " . rarFormats
retStr .= "`nrarFormatsNoP = " . rarFormatsNoP

retStr .= "`nmgEnabled = " . mgEnabled
retStr .= "`nmgKey = " . mgKey
retStr .= "`nmgSelectKey = " . mgSelectKey
retStr .= "`nmgExitKey = " . mgExitKey
retStr .= "`nmultiGameImgPath = " . multiGameImgPath
retStr .= "`nmgBackgroundColor = " . mgBackgroundColor
retStr .= "`nmgSidePadding = " . mgSidePadding
retStr .= "`nmgYOffset = " . mgYOffset
retStr .= "`nmgImageAdjust = " . mgImageAdjust
retStr .= "`nmgFont = " . mgFont
retStr .= "`nmgText1Options = " . mgText1Options
retStr .= "`nmgText1Text = " . mgText1Text
retStr .= "`nmgText2Options = " . mgText2Options
retStr .= "`nmgText2Offset = " . mgText2Offset
retStr .= "`nmgUseSound = " . mgUseSound
retStr .= "`nmgSoundfreq = " . mgSoundfreq
retStr .= "`nmgExitEffect = " . mgExitEffect
retStr .= "`nmgSelectedEffect = " . mgSelectedEffect
retStr .= "`nmgUseGameArt = " . mgUseGameArt
retStr .= "`nmgArtworkDir = " . mgArtworkDir

If cpWizardEnabled = true
{
	If cpWizardPath != ""
	{
		checkFile(cpWizardPath)
		retStr .= "`ncpWizardPath = " . cpWizardPath
		retStr .= "`ncpWizardDelay = " . cpWizardDelay
		retStr .= "`ncpWizardParams = " . cpWizardParams
	}Else{
		MsgBox Missing CPWizard Path and CPWizard is enabled
		ExitScript()
	}
} 

;Common to all modules, sets the exit key
;But this means all scripts no matter what require a CloseProcess
;whether its used or not.
retStr .= "`nHotkey, " . exitEmulatorKey . ", CloseProcess"

retStr .= "`n;-----------------------------------------------------------"
retStr .= "`n;Module script"
retStr .= "`n;-----------------------------------------------------------"

;Run CPWizard
If cpWizardEnabled = true
{
	Log("Running CPWizard")
	; retStr .= "`nRun`, ""%cpWizardPath%"" -emu ""%systemName%"" -game ""%romName%"" ""%cpWizardParams%"""
	retStr .= "`nRun`, ""%cpWizardPath%"" -emu ""%systemName%"" -game ""%romName%"" %cpWizardParams%"
	retStr .= "`nSleep`, %cpWizardDelay%"
}

;Add MultiGame hotkey if needed by the system
If mgEnabled = true
{
	If !FileExist(moduleExtensionPath . "Gdip.ahk") {
		IfNotExist, % moduleExtensionPath
			FileCreateDir, % moduleExtensionPath ; Need to create the folder first otherwise urldownload will fail
		UrlDownloadToFile, http://www.autohotkey.net/~tic/Gdip.ahk, % moduleExtensionPath . "Gdip.ahk"
		If ErrorLevel
			ScriptError("Error downloading gdip.ahk to the """"modules\Module Extensions\"""" folder.`n Either donwload is unavailable or  admin privledges are needed to write to this folder.")
	}
	retStr .= "`n`n#Include`, *i %A_ScriptDir%\Modules\Module Extensions\Gdip.ahk`nSetBatchLines`, -1`nHotkey`, %mgKey%`, StartMulti"
}

;Now insert the module script 
;We have to add each line individually for this to work
Loop, Read, %moduleFile%
{
	retStr .= "`n" . A_LoopReadLine
}

;Add Global HideDesktop function to module if it is used
; If addHideDesktop = true && hideDesktop = true
	retStr .= "`n`nhideDesktop(){`nGui`, Color`, 000000 `nGui -Caption +ToolWindow `nGui`, Show`, x0 y0 W%A_ScreenWidth% H%A_ScreenHeight%`, BlackScreen`n}" ; +AlwaysOnTop
; Else{
	;Still have to add a blank function so no error occurs.
	;This allows users to turn off desktop hiding even if the module writers make a call for it.
	; retStr .= "`n`nhideDesktop(){`n}"
; }

;Add Daemon Tools function to module if it is used
If addDaemonTools = true
	retStr .= "`n`nDaemonTools(action`,type=""dt""`,drive=0`,addDrive=""true""`,file=""""){`nGlobal daemonToolsPath`nfile := (If file ? (""``, """""" . file . """""""") : (""""))`nIfNotExist % daemonToolsPath`nScriptError(""Could not find "" . daemonToolsPath . ""``nPlease fix the path_to_daemontools key in your Settings\Global Settings.ini to point to your DTLite installation.""`,8)`nIf action not in mount`,unmount`nScriptError(action . "" is an unsupported use of daemontools. Only mount and unmount actions are supported."")`nIf type not in dt`,scsi`nScriptError(type . "" is an unsupported use of daemontools. Only dt and scsi drives are supported."")`nIf drive not in 0`,1`,2`,3`,4`nScriptError(drive . "" is an invalid virtual device number. Only 0 through 4 are supported."")`nRunWait`, %daemonToolsPath% -get_count %type%`nIf (ErrorLevel = 0 && addDrive != ""false"")`nRunWait`, %daemonToolsPath% -add %type%`nElse If ErrorLevel = 0`nScriptError(""You are trying to mount to a "" . type . "" virtual drive`, yet one does not exist."")`nRunWait`, %daemonToolsPath% -%action% %type%``, %drive%%file%`n}`n"

;Add Global FadeIn functions to module if they are used
If fadeIn = true
{
	retStr .= "`n`nFadeInStart(){`nStatic topPicSize`nStatic middlePicSize`nStatic bottomPicSize`nGlobal systemName`nGlobal fadeIn`nGlobal fadeColor`nGlobal fadeInDuration`nGlobal fadeInDelay`nGlobal fadeInInterruptKeys`nGlobal gameStartImgPath`nGlobal romName`nIf ( fadeIn = ""true"" ) {`ntopPic = %gameStartImgPath%top.png`nIfExist`, %gameStartImgPath%%romName%.png`nmiddlePic = %gameStartImgPath%%romName%.png`nElse`nmiddlePic = %gameStartImgPath%middle.png`nbottomPic = %gameStartImgPath%bottom.png`nGui`, 99:add`, picture`, vtopPicSize`, %topPic%`nGui`, 99:add`, picture`, vmiddlePicSize`, %middlePic%`nGui`, 99:add`, picture`, vbottomPicSize`, %bottomPic%`nGuiControlGet`, topPicSize`, 99:Pos`nGuiControlGet`, middlePicSize`, 99:Pos`nGuiControlGet`, bottomPicSize`, 99:Pos`nGui`, 99:destroy`nGui +LastFound`nWinGet GUI_ID`, ID`nGui +AlwaysOnTop -Caption +ToolWindow`nGui`, Color`, %fadeColor%`ntopXPos := ( A_ScreenWidth / 2 ) - ( topPicSizeW / 2 )`ntopYPos := 25`nmiddleXPos := ( A_ScreenWidth / 2 ) - ( middlePicSizeW / 2 )`nmiddleYPos := ( A_ScreenHeight / 2 ) - ( middlePicSizeH / 2 )`nbottomXPos := ( A_ScreenWidth / 2 ) - ( bottomPicSizeW / 2 )`nbottomYPos := ( A_ScreenHeight - bottomPicSizeH - 25 )`nGui`, Add`, Picture`,x%topXPos% y%topYPos%`, %topPic%`nGui`, Add`, Picture`,x%middleXPos% y%middleYPos%`, %middlePic%`nGui`, Add`, Picture`,x%bottomXPos% y%bottomYPos%`, %bottomPic%`nGui Show`, x0 y0 h%A_ScreenHeight% w%A_ScreenWidth% Hide`nDllCall(""AnimateWindow""`,""UInt""`,GUI_ID`,""Int""`,fadeInDuration`,""UInt""`,""0xa0000"")`nIf A_OSVersion In WIN_7,WIN_VISTA,WIN_XP`n{`nSetFormat`, Float`, 6.3`nfadeInDelay := (fadeInDelay/1000)`nfadeInDelay := (If fadeInDelay < 1 ? (""1"") : (fadeInDelay))`nInput`, SingleKey`, L1 T%fadeInDelay%, %fadeInInterruptKeys%`n} Else`nSleep`, %fadeInDelay%`nReturn GUI_ID`n}`n}"
	retStr .= "`n`nFadeInExit(){`nGlobal fadeIn`nGlobal fadeInDuration`nGlobal GUI_ID`nIf ( fadeIn = ""true"" ) {`nDllCall(""AnimateWindow""`,UInt`,GUI_ID`,UInt`,fadeInDuration`,UInt`,0x90000)`nGui Destroy`n}`n}"
}Else{
	; Still have to add a blank function so no error occurs.
	retStr .= "`n`nFadeInStart(){`n}"
	retStr .= "`n`nFadeInExit(){`n}"
}


;Add Global FadeOut functions to module if they are used
If fadeOut = true
{
	retStr .= "`n`nFadeOutStart(){`nSuspend`, On`nGlobal fadeOut`nGlobal fadeColor`nGlobal fadeOutDuration`nIf ( fadeOut = ""true"" ) {`nGui +LastFound`nWinGet GUI_ID3`, ID`nGui +AlwaysOnTop -Caption +ToolWindow`nGui Color`, %fadeColor%`nGui Show`, x0 y0 h%A_ScreenHeight% w%A_ScreenWidth% Hide`nDllCall(""AnimateWindow""`,""UInt""`,GUI_ID3`,""Int""`,fadeOutDuration`,""UInt""`,""0xa0000"")`n}`nReturn GUI_ID3`n}"
	retStr .= "`n`nFadeOutExit(){`nGlobal fadeOut`nGlobal fadeOutDuration`nGlobal GUI_ID3`nIf ( fadeOut = ""true"" ) {`nDllCall(""AnimateWindow""`,UInt`,GUI_ID3`,UInt`,fadeOutDuration`,UInt`,0x90000)`n}`n}"
}Else{
	;Still have to add a blank function so no error occurs.
	retStr .= "`n`nFadeOutStart(){`nSuspend`, On`n}"
	retStr .= "`n`nFadeOutExit(){`n}"
}

;Add 7z related functions to module if it is used
;Extracting rom if emulator doesn't support the compressed file type
If 7zEnable = true
{

; old function, before byref retStr .= "`n`n7z(path`, name`, ext`, ByRef 7zExtractDir){`nGlobal 7zEnable`nGlobal 7zFormats`nGlobal 7zFormatsNoP`nGlobal romExtensions`nGlobal romExtension`nGlobal romPath`nGlobal skipchecks`nIf ( 7zEnable = ""true"" ) {`n If romExtension in %7zFormats%`n{`nCheckForRomExt()`n7zPath = %A_ScriptDir%\7z.exe`n7zList := StdoutToVar_CreateProcess(7zPath . "" l """""" . path . name . ext . """""""")`nLoop`, Parse`, romExtensions`, ``,`n{`nIf ( skipchecks != ""true"" ) {`nIf A_LoopField in %7zFormatsNoP%`nContinue`n}`n7zExtractDirCheck = %7zExtractDir%HS\%name%\`nIfExist`, %7zExtractDirCheck%%name%.%A_LoopField%`n{`nromExtension = .%A_LoopField%`nromFound = true`n7zExtractDir = %7zExtractDirCheck%`nBreak`n}`nromIn7z := (InStr(7zList`, name . ""."" . A_LoopField) ? (""true"") : (""false""))`nIf ( romIn7z = ""true"" || skipchecks = ""true"" ) {`n7zExtractDir = %7zExtractDirCheck%`nRunWait`, %7zPath% e ""%path%%name%%ext%"" -aoa -o ""%7zExtractDir%""`,`,Hide`nIf ( ErrorLevel != 0 ) {`nIf ( ErrorLevel = 1 ) {`nError = Non fatal error, file may be in use by another application`n} Else If ( ErrorLevel = 2 ) {`nError = Fatal Error`n} Else If ( ErrorLevel = 7 ) {`nError = Command line error`n} Else If ( ErrorLevel = 8 ) {`nError = Not enough memory for operation`n} Else If ( ErrorLevel = 255 ) {`nError = User stopped the process`n} Else {`nError = Unknown 7zip Error`n}`nMsgBox`, 48`, 7zip.exe Error`, %Error%`, 5`nExitApp`n}`nIf (FileExist(7zExtractDir . name . ""."" . A_LoopField) || skipchecks = ""true"") { `nromExtension = .%A_LoopField% `nromFound = true`nBreak`n} Else`nromFound = false`n}`n}`nIf ( romFound = ""false"" )`nScriptError(""No extracted files found in "" . 7zExtractDir . ""``nCheck if you are exceeding the 255 character limit."")`nromPath = %7zExtractDir%`n}`n}`n}"
;	retStr .= "`n`n7z(ByRef 7zP`, ByRef 7zN`, ByRef 7zE`, ByRef 7zExtractDir){`nGlobal 7zEnable`nGlobal 7zFormats`nGlobal 7zFormatsNoP`nGlobal romExtensions`nGlobal skipchecks`nIf ( 7zEnable = ""true"" ) {`nIf 7zE in %7zFormats%`n{`nCheckForRomExt()`n7zPath = %A_ScriptDir%\7z.exe`n7zList := StdoutToVar_CreateProcess(7zPath . "" l """""" . 7zP . 7zN . 7zE . """""""")`nLoop`, Parse`, romExtensions`, ``,`n{`nIf ( skipchecks != ""true"" ) {`nIf A_LoopField in %7zFormatsNoP%`nContinue`n}`n7zExtractDirCheck = %7zExtractDir%HS\%7zN%\`nIfExist`, %7zExtractDirCheck%%7zN%.%A_LoopField%`n{`n7zE = .%A_LoopField%`nromFound = true`n7zExtractDir = %7zExtractDirCheck%`nBreak`n}`nromIn7z := (InStr(7zList`, 7zN . ""."" . A_LoopField) ? (""true"") : (""false""))`nIf ( romIn7z = ""true"" || skipchecks = ""true"" ) {`n7zExtractDir = %7zExtractDirCheck%`nRunWait`, %7zPath% x ""%7zP%%7zN%%7zE%"" -aoa -o""%7zExtractDir%""`,`,Hide`nIf ( ErrorLevel != 0 ) {`nIf ( ErrorLevel = 1 ) {`nError = Non fatal error, file may be in use by another application`n} Else If ( ErrorLevel = 2 ) {`nError = Fatal Error`n} Else If ( ErrorLevel = 7 ) {`nError = Command line error`n} Else If ( ErrorLevel = 8 ) {`nError = Not enough memory for operation`n} Else If ( ErrorLevel = 255 ) {`nError = User stopped the process`n} Else {`nError = Unknown 7zip Error`n}`nMsgBox`, 48`, 7zip.exe Error`, %Error%`, 5`nExitApp`n}`nIf (FileExist(7zExtractDir . 7zN . ""."" . A_LoopField) || skipchecks = ""true"") {`n7zE = .%A_LoopField% `nromFound = true`nBreak`n} Else`nromFound = false`n}`n}`nIf ( romFound = ""false"" )`nScriptError(""No extracted files found in "" . 7zExtractDir . ""``nCheck if you are exceeding the 255 character limit."")`n7zP = %7zExtractDir%`n}`n}`n}"
;	retStr .= "`n`n7z(ByRef 7zP`, ByRef 7zN`, ByRef 7zE`, ByRef 7zExtractDir){`nGlobal 7zEnable`nGlobal 7zFormats`nGlobal 7zFormatsNoP`nGlobal romExtensions`nGlobal skipchecks`nIf ( 7zEnable = ""true"" ) {`nIf 7zE in %7zFormats%`n{`nCheckForRomExt()`n7zPath = %A_ScriptDir%\7z.exe`n7zList := StdoutToVar_CreateProcess(7zPath . "" l """""" . 7zP . 7zN . 7zE . """""""")`nLoop`, Parse`, romExtensions`, ``,`n{`nIf ( skipchecks != ""true"" ) {`nIf A_LoopField in %7zFormatsNoP%`nContinue`n}`n7zExtractDirCheck = %7zExtractDir%HS\%7zN%\`nIfExist`, %7zExtractDirCheck%%7zN%.%A_LoopField%`n{`n7zE = .%A_LoopField%`nromFound = true`n7zExtractDir = %7zExtractDirCheck%`nBreak`n}`nromIn7z := (InStr(7zList`, 7zN . ""."" . A_LoopField) ? (""true"") : (""false""))`nIf ( romIn7z = ""true"" || skipchecks = ""true"" ) {`n7zExtractDir = %7zExtractDirCheck%`nRunWait`, %7zPath% x ""%7zP%%7zN%%7zE%"" -aoa -o""%7zExtractDir%""`,`,Hide`nIf ( ErrorLevel != 0 ) {`nIf ( ErrorLevel = 1 )`nError = Non fatal error`, file may be in use by another application`nElse If ( ErrorLevel = 2 )`nError = Fatal Error`nElse If ( ErrorLevel = 7 )`nError = Command line error`nElse If ( ErrorLevel = 8 )`nError = Not enough memory for operation`nElse If ( ErrorLevel = 255 )`nError = User stopped the process`nElse`nError = Unknown 7zip Error`nMsgBox`, 48`, 7zip.exe Error`, %Error%`, 5`nExitApp`n}`nIf (FileExist(7zExtractDir . 7zN . ""."" . A_LoopField) || skipchecks = ""true"") {`n7zE = .%A_LoopField% `nromFound = true`nBreak`n} Else`nromFound = false`n}`n}`nIf ( romFound = ""false"" )`nScriptError(""No extracted files found in "" . 7zExtractDir . ""``nCheck if you are exceeding the 255 character limit."")`n7zP = %7zExtractDir%`n}`n}`n}"


	retStr .= "`n`n7z(ByRef 7zP`, ByRef 7zN`, ByRef 7zE`, ByRef 7zExtractDir){`nGlobal 7zEnable`nGlobal 7zFormats`nGlobal 7zFormatsNoP`nGlobal romExtensions`nGlobal skipchecks`nIf ( 7zEnable = ""true"" ) {`nIf 7zE in %7zFormats%`n{`nCheckForRomExt()`n7zPath = %A_ScriptDir%\7z.exe`n7zList := StdoutToVar_CreateProcess(7zPath . "" l """""" . 7zP . 7zN . 7zE . """""""")`nclipboard = % 7zlist`nLoop`, Parse`, romExtensions`, ``,`n{`nIf A_LoopField in %7zFormatsNoP%`nContinue`n7zExtractDirCheck = %7zExtractDir%HS\%7zN%\`nIfExist`, %7zExtractDirCheck%%7zN%.%A_LoopField%`n{`n7zE = .%A_LoopField%`nromFound = true`n7zExtractDir = %7zExtractDirCheck%`nBreak`n}`nromIn7z := (InStr(7zList`, 7zN . ""."" . A_LoopField) ? (""true"") : (""false""))`nIf ( romIn7z = ""true"" || skipchecks = ""true"" ) {`n7zExtractDir = %7zExtractDirCheck%`nRunWait`, %7zPath% x ""%7zP%%7zN%%7zE%"" -aoa -o""%7zExtractDir%""`,`,Hide`nIf ( ErrorLevel != 0 ) {`nIf ( ErrorLevel = 1 )`nError = Non fatal error`, file may be in use by another application`nElse If ( ErrorLevel = 2 )`nError = Fatal Error`nElse If ( ErrorLevel = 7 )`nError = Command line error`nElse If ( ErrorLevel = 8 )`nError = Not enough memory for operation`nElse If ( ErrorLevel = 255 )`nError = User stopped the process`nElse`nError = Unknown 7zip Error`nMsgBox`, 48`, 7zip.exe Error`, %Error%`, 5`nExitApp`n}`nIf (FileExist(7zExtractDir . 7zN . ""."" . A_LoopField) || skipchecks = ""true"") {`n7zE = .%A_LoopField%`nromFound = true`nBreak`n} Else {`nromFound = false`nfoundExt := ""."" . A_LoopField`n}`n}`n}`nIf ( romFound = ""false"" )`nScriptError(""No extracted files found in "" . 7zExtractDir . ""``nCheck that you are not exceeding the 255 character limit and this file is in the root of your archive:``n"" . 7zN . foundExt`,10)`n7zP = %7zExtractDir%`n}`n}`n}"
	retStr .= "`n`nStdoutToVar_CreateProcess(sCmd`, bStream = False`, sDir = """"`, sInput = """")`n{`nDllCall(""CreatePipe""`, ""UintP""`, hStdInRd `, ""UintP""`, hStdInWr `, ""Uint""`, 0`, ""Uint""`, 0)`nDllCall(""CreatePipe""`, ""UintP""`, hStdOutRd`, ""UintP""`, hStdOutWr`, ""Uint""`, 0`, ""Uint""`, 0)`nDllCall(""SetHandleInformation""`, ""Uint""`, hStdInRd `, ""Uint""`, 1`, ""Uint""`, 1)`nDllCall(""SetHandleInformation""`, ""Uint""`, hStdOutWr`, ""Uint""`, 1`, ""Uint""`, 1)`nVarSetCapacity(pi`, 16`, 0)`nNumPut(VarSetCapacity(si`, 68`, 0)`, si)`nNumPut(0x100	`, si`, 44)`nNumPut(hStdInRd	`, si`, 56)`nNumPut(hStdOutWr`, si`, 60)`nNumPut(hStdOutWr`, si`, 64)`nIf Not	DllCall(""CreateProcess""`, ""Uint""`, 0`, ""Uint""`, &sCmd`, ""Uint""`, 0`, ""Uint""`, 0`, ""int""`, True`, ""Uint""`, 0x08000000`, ""Uint""`, 0`, ""Uint""`, sDir ? &sDir : 0`, ""Uint""`, &si`, ""Uint""`, π)`nExitApp`nDllCall(""CloseHandle""`, ""Uint""`, NumGet(pi`,0))`nDllCall(""CloseHandle""`, ""Uint""`, NumGet(pi`,4))`nDllCall(""CloseHandle""`, ""Uint""`, hStdOutWr)`nDllCall(""CloseHandle""`, ""Uint""`, hStdInRd)`nIf	sInput <>`nDllCall(""WriteFile""`, ""Uint""`, hStdInWr`, ""Uint""`, &sInput`, ""Uint""`, StrLen(sInput)`, ""UintP""`, nSize`, ""Uint""`, 0)`nDllCall(""CloseHandle""`, ""Uint""`, hStdInWr)`nbStream ? (bAlloc:=DllCall(""AllocConsole"")`,hCon:=DllCall(""CreateFile""`,""str""`,""CON""`,""Uint""`,0x40000000`,""Uint""`,bAlloc ? 0 : 3`,""Uint""`,0`,""Uint""`,3`,""Uint""`,0`,""Uint""`,0)) : """"`nVarSetCapacity(sTemp`, nTemp:=bStream ? 64-nTrim:=1 : 4095)`nLoop`nIf	DllCall(""ReadFile""`, ""Uint""`, hStdOutRd`, ""Uint""`, &sTemp`, ""Uint""`, nTemp`, ""UintP""`, nSize:=0`, ""Uint""`, 0)&&nSize`n{`nNumPut(0`,sTemp`,nSize`,""Uchar"")`, VarSetCapacity(sTemp`,-1)`, sOutput.=sTemp`nIf	bStream&&hCon+1`nLoop`nIf	RegExMatch(sOutput`, ""[^\n]*\n""`, sTrim`, nTrim)`nDllCall(""WriteFile""`, ""Uint""`, hCon`, ""Uint""`, &sTrim`, ""Uint""`, StrLen(sTrim)`, ""UintP""`, nSize:=0`, ""Uint""`, 0)&&nSize ? nTrim+=nSize : """"`nElse	Break`n}`nElse	Break`nDllCall(""CloseHandle""`, ""Uint""`, hStdOutRd)`nbStream ? (DllCall(""Sleep""`,""Uint""`,1000)`,hCon+1 ? DllCall(""CloseHandle""`,""Uint""`,hCon) : """"`,bAlloc ? DllCall(""FreeConsole"") : """") : """"`nReturn sOutput`n}"
	retStr .= "`n`nCheckForRomExt() {`nGlobal romExtensions`nGlobal 7zFormatsNoP`nGlobal skipchecks`nIf ( skipchecks != ""true"" ) {`nLoop`, Parse`, romExtensions`, ```,`n{`nIf A_LoopField in %7zFormatsNoP%`n{`nnotFound = 1`nContinue`n} Else`nReturn`n}`nIf notFound = 1`nScriptError(""You did not supply any valid rom extensions to search for in your compressed roms."")`n}`n}"
	retStr .= "`n`n7zCleanUp() {`nGlobal romTable`nGlobal 7zDelTemp`nGlobal 7zExtractDir`nGlobal mgEnabled`nIf 7zDelTemp = true`n{`nromTableExists := IsObject(romTable)`nIf (mgEnabled = ""true""  && romTableExists)`n{`nfor index`, element in romTable`nIf % romTable[A_Index`, 15]`nFileRemoveDir`, % romTable[A_Index`, 15]`, 1`nFileRemoveDir`, %7zExtractDir%`, 1`n} Else`nFileRemoveDir`, %7zExtractDir%`, 1`n}`n}"

}Else{

	;Still have to add blank functions so no error occurs.
	retStr .= "`n`n7z(7zP`, 7zN`, 7zE`, 7zExtractDir){`n}"
	retStr .= "`n`n7zCleanUp() {`n}"
}


;Added by Tastyratz for Winrar support +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+----------
;Added by Tastyratz for Winrar support +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+----------

If rarEnable = true
{
	retStr .= "`n`nrar(ByRef rarP`, ByRef rarN`, ByRef rarE`, ByRef rarExtractDir){`nGlobal rarEnable`nGlobal rarFormats`nGlobal rarFormatsNoP`nGlobal romExtensions`nGlobal skipchecks`nIf ( rarEnable = ""true"" ) {`nIf rarE in %rarFormats%`n{`nCheckForRomExt()`nrarPath = %A_ScriptDir%\unrar.exe`nrarList := StdoutToVar_CreateProcess(rarPath . "" l """""" . rarP . rarN . rarE . """""""")`nclipboard = % rarlist`nLoop`, Parse`, romExtensions`, ``,`n{`nIf A_LoopField in %rarFormatsNoP%`nContinue`nrarExtractDirCheck = %rarExtractDir%\HS\%rarN%\`nIfExist`, %rarExtractDirCheck%%rarN%.%A_LoopField%`n{`nrarE = .%A_LoopField%`nromFound = true`nrarExtractDir = %rarExtractDirCheck%`nBreak`n}`nromInrar := (InStr(rarList`, rarN . ""."" . A_LoopField) ? (""true"") : (""false""))`nIf ( romInrar = ""true"" || skipchecks = ""true"" ) {`nrarExtractDir = %rarExtractDirCheck%`nRunWait`, %rarPath% x -o+ ""%rarP%%rarN%%rarE%"" ""%rarExtractDir%""`,`,Hide`nIf ( ErrorLevel != 0 ) {`nIf ( ErrorLevel = 1 )`nError = Non fatal error`, file may be in use by another application`nElse If ( ErrorLevel = 2 )`nError = Fatal Error`nElse If ( ErrorLevel = 7 )`nError = Command line error`nElse If ( ErrorLevel = 8 )`nError = Not enough memory for operation`nElse If ( ErrorLevel = 255 )`nError = User stopped the process`nElse`nError = Unknown unrar Error`nMsgBox`, 48`, unrar.exe Error`, %Error%`, 5`nExitApp`n}`nIf (FileExist(rarExtractDir . rarN . ""."" . A_LoopField) || skipchecks = ""true"") {`nrarE = .%A_LoopField%`nromFound = true`nBreak`n} Else {`nromFound = false`nfoundExt := ""."" . A_LoopField`n}`n}`n}`nIf ( romFound = ""false"" )`nScriptError(""No extracted files found in "" . rarExtractDir . ""``nCheck that you in this path are not exceeding the 255 character limit and this file is in the root of your archive:``n"" . rarN . foundExt`,10)`nrarP = %rarExtractDir%`n}`n}`n}"

	retStr .= "`n`nStdoutToVar_CreaterarProcess(sCmd`, bStream = False`, sDir = """"`, sinput = """")`n{`nDllCall(""CreatePipe""`, ""UintP""`, hStdInRd `, ""UintP""`, hStdInWr `, ""Uint""`, 0`, ""Uint""`, 0)`nDllCall(""CreatePipe""`, ""UintP""`, hStdOutRd`, ""UintP""`, hStdOutWr`, ""Uint""`, 0`, ""Uint""`, 0)`nDllCall(""SetHandleInformation""`, ""Uint""`, hStdInRd `, ""Uint""`, 1`, ""Uint""`, 1)`nDllCall(""SetHandleInformation""`, ""Uint""`, hStdOutWr`, ""Uint""`, 1`, ""Uint""`, 1)`nVarSetCapacity(pi`, 16`, 0)`nNumPut(VarSetCapacity(si`, 68`, 0)`, si)`nNumPut(0x100	`, si`, 44)`nNumPut(hStdInRd	`, si`, 56)`nNumPut(hStdOutWr`, si`, 60)`nNumPut(hStdOutWr`, si`, 64)`nIf Not	DllCall(""CreateProcess""`, ""Uint""`, 0`, ""Uint""`, &sCmd`, ""Uint""`, 0`, ""Uint""`, 0`, ""int""`, True`, ""Uint""`, 0x08000000`, ""Uint""`, 0`, ""Uint""`, sDir ? &sDir : 0`, ""Uint""`, &si`, ""Uint""`, π)`nExitApp`nDllCall(""CloseHandle""`, ""Uint""`, NumGet(pi`,0))`nDllCall(""CloseHandle""`, ""Uint""`, NumGet(pi`,4))`nDllCall(""CloseHandle""`, ""Uint""`, hStdOutWr)`nDllCall(""CloseHandle""`, ""Uint""`, hStdInRd)`nIf	sinput <>`nDllCall(""WriteFile""`, ""Uint""`, hStdInWr`, ""Uint""`, &sinput`, ""Uint""`, StrLen(sinput)`, ""UintP""`, nSize`, ""Uint""`, 0)`nDllCall(""CloseHandle""`, ""Uint""`, hStdInWr)`nbStream ? (bAlloc:=DllCall(""AllocConsole"")`,hCon:=DllCall(""CreateFile""`,""str""`,""CON""`,""Uint""`,0x40000000`,""Uint""`,bAlloc ? 0 : 3`,""Uint""`,0`,""Uint""`,3`,""Uint""`,0`,""Uint""`,0)) : """"`nVarSetCapacity(sTemp`, nTemp:=bStream ? 64-nTrim:=1 : 4095)`nLoop`nIf	DllCall(""ReadFile""`, ""Uint""`, hStdOutRd`, ""Uint""`, &sTemp`, ""Uint""`, nTemp`, ""UintP""`, nSize:=0`, ""Uint""`, 0)&&nSize`n{`nNumPut(0`,sTemp`,nSize`,""Uchar"")`, VarSetCapacity(sTemp`,-1)`, sOutput.=sTemp`nIf	bStream&&hCon+1`nLoop`nIf	RegExMatch(sOutput`, ""[^\n]*\n""`, sTrim`, nTrim)`nDllCall(""WriteFile""`, ""Uint""`, hCon`, ""Uint""`, &sTrim`, ""Uint""`, StrLen(sTrim)`, ""UintP""`, nSize:=0`, ""Uint""`, 0)&&nSize ? nTrim+=nSize : """"`nElse	Break`n}`nElse	Break`nDllCall(""CloseHandle""`, ""Uint""`, hStdOutRd)`nbStream ? (DllCall(""Sleep""`,""Uint""`,1000)`,hCon+1 ? DllCall(""CloseHandle""`,""Uint""`,hCon) : """"`,bAlloc ? DllCall(""FreeConsole"") : """") : """"`nReturn sOutput`n}"

	retStr .= "`n`nCheckForRomExtrar() {`nGlobal romExtensions`nGlobal rarFormatsNoP`nGlobal skipchecks`nIf ( skipchecks != ""true"" ) {`nLoop`, Parse`, romExtensions`, ```,`n{`nIf A_LoopField in %rarFormatsNoP%`n{`nnotFound = 1`nContinue`n} Else`nReturn`n}`nIf notFound = 1`nScriptError(""You did not supply any valid rom extensions to search for in your compressed roms."")`n}`n}"

	retStr .= "`n`nrarCleanUp() {`nGlobal romTable`nGlobal rarDelTemp`nGlobal rarExtractDir`nGlobal mgEnabled`nIf rarDelTemp = true`n{`nromTableExists := IsObject(romTable)`nIf (mgEnabled = ""true""  && romTableExists)`n{`nfor index`, element in romTable`nIf % romTable[A_Index`, 15]`nFileRemoveDir`, % romTable[A_Index`, 15]`, 1`nFileRemoveDir`, %rarExtractDir%`, 1`n} Else`nFileRemoveDir`, %rarExtractDir%`, 1`n}`n}"
}Else{
	;Still have to add blank functions so no error occurs.
	retStr .= "`n`nrar(rarP`, rarN`, rarE`, rarExtractDir){`n}"
	retStr .= "`n`nrarCleanUp() {`n}"
}

;Added by Tastyratz for Winrar support +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+----------
;Added by Tastyratz for Winrar support +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+----------





;Add MultiGame labels and functions if needed by the system
If mgEnabled = true
	retStr .= "`n`nStartMulti:`nHotkey`, %mgKey%`, Off`nmultiTypes = (Cart`,(Disc`,(Disk`,(Tape`ncurrentButton:=1`nmgCancel:=0`nangle:=0`nb:=1`nmgGrowing:=`n`nIf romName not contains %multiTypes%`nReturn`nIf romExtensionOrig contains %7zFormats%`nIf % 7zEnable = ""true""`nromNeeds7z:=1`n`nIf !romTable`nromTable:=CreateRomTable(romName)`n`nIf !romTable.MaxIndex() {`nToolTip`, This game does not need Multi-Game support`, 0`, 0`nSleep`, 1000`nToolTip`nReturn`n}`n`nIf !pToken := Gdip_Startup()`n{`nScriptError(""Gdiplus failed to start. Please ensure you have gdiplus on your system"")`nExitApp`n}`n`nGosub`, PreMultiGame`n`nmgW := A_ScreenWidth`, mgH := A_ScreenHeight`nLoop`, 2 {`nGui`, %A_Index%: -Caption +E0x80000 +LastFound +OwnDialogs +Owner +AlwaysOnTop`nGui`, %A_Index%: Margin`,0`,0`nGui`, %A_Index%: Show`,`, Layer%A_Index%`nhwnd%A_Index% := WinExist()`n`nhbm%A_Index% := CreateDIBSection(mgW`, mgH)`, hdc%A_Index% := CreateCompatibleDC()`, obm%A_Index% := SelectObject(hdc%A_Index%`, hbm%A_Index%)`nG%A_Index% := Gdip_GraphicsFromhdc(hdc%A_Index%)`n}`nGdip_SetInterpolationMode(G1`, 7)`n`nIf !hFamily := Gdip_FontFamilyCreate(mgFont)`n{`nScriptError(""The mgFont "" . mgFont . "" you have specified does not exist on the system"")`nExitApp`n}`nGdip_DeleteFontFamily(hFamily)`n`nIfExist`, % multiGameImgPath . romName . "".png""`nmultiBG:=multiGameImgPath . romName . "".png""`nElse IfExist`, % multiGameImgPath . ""default.png""`nmultiBG:=multiGameImgPath . ""default.png""`nElse`nmultiBG:=`n`nLoop`, 2 {`nImage_%A_Index% := multiGameImgPath . romTable[A_Index`,5] . ""_image_"" . A_Index . "".png""`nIf !FileExist(Image_%A_Index%) {`nToolTip`, Downloading Image %A_Index%`,0`,0`nIfNotExist`, % multiGameImgPath`nFileCreateDir`, % multiGameImgPath`nUrlDownloadToFile`, % ""http://www.hyperspin-fe.com/HL2/"" . romTable[A_Index`,5] . ""_image_"" . A_Index . "".png""`, % multiGameImgPath . romTable[A_Index`,5] . ""_image_"" . A_Index . "".png""`nIf ErrorLevel`nScriptError(""Error connecting to www.hyperspin-fe.com to download images. Please try again later or report the problem it it persists."")`n}`nToolTip`n}`n`nfor index`, element in romTable`n{`nIf FileExist(A_ScriptDir . ""\Media\"" . systemName . ""\Images\"" . mgArtworkDir . ""\"" . romTable[A_Index`, 3] . "".png"") && (mgUseGameArt = ""true"" ) {`nromTable[A_Index`, 13] := Gdip_CreateBitmapFromFile(A_ScriptDir . ""\Media\"" . systemName . ""\Images\"" . mgArtworkDir . ""\"" . romTable[A_Index`, 3] . "".png"")`nIf !romTable[A_Index`, 13] {`nMsgBox`, 16`, Error Loading MultiGame Artwork %A_Index%`, % ""Could not find "" .  romTable[A_Index`,3] . "".png. Please try again later or report the problem if it persists.""`,5`nGoto`, MGExit`n}`nromTable[A_Index`,12] := ""Yes""`n} Else {`nromTable[A_Index`, 13] := Gdip_CreateBitmapFromFile(Image_1)`nromTable[A_Index`, 14] := Gdip_CreateBitmapFromFile(Image_2)`n}`nGdip_GetImageDimensions(romTable[A_Index`, 13]`, mgArtW`, mgArtH)`nromTable[A_Index`,8] := mgArtW`, romTable[A_Index`,9] := mgArtH`nromTable[A_Index`,10] := romTable[A_Index`,8]*mgImageAdjust`, romTable[A_Index`,11] := romTable[A_Index`,9]*mgImageAdjust`nIf mgSelectedEffect = rotate`n{`nGdip_GetRotatedDimensions(romTable[A_Index`, 10]`, romTable[A_Index`, 11]`, 90`, mgRW%A_Index%`, mgRH%A_Index%)`nmgRW%A_Index% := (mgRW%A_Index% > romTable[A_Index`, 10]) ? mgRW%A_Index%* : romTable[A_Index`, 10]`, mgRH%A_Index% := (mgRH%A_Index% > romTable[A_Index`, 11]) ? mgRH%A_Index% : romTable[A_Index`, 11]`n}`n}`n`ntotalUnusedWidth := mgW - ( romTable[1`, 10] * romTable.MaxIndex() )`nremainingUnusedWidth := totalUnusedWidth * ( 1 - ( mgSidePadding * 2 ))`npaddingSpotsNeeded := romTable.MaxIndex() - 1`nimageSpacing := remainingUnusedWidth//paddingSpotsNeeded`nimageX:=mgSidePadding * totalUnusedWidth`nimageXcurrent:=imageX`n`nIf MultiBG {`nmBGBitmap := Gdip_CreateBitmapFromFile(multiBG)`nGdip_GetImageDimensions(mBGBitmap`, mBGw`, mBGh)`nGdip_DrawImage(G1`, mBGBitmap`, 0`, 0`, mgW+1`, mgH+1`, 0`, 0`, mBGw`, mBGh)`n} Else {`npBrush := Gdip_BrushCreateSolid(""0x"" . mgBackgroundColor)`nGdip_FillRectangle(G1`, pBrush`, -1`, -1`, mgW+1`, mgH+1)`n}`n`nGdip_TextToGraphics(G1`, mgText1Text`, mgText1Options`, mgFont`, mgW`, mgH)`n`nfor index`, element in romTable {`nromTable[A_Index`,6] := (If romTable[A_Index`,12] ? (imageXcurrent) : (imageXcurrent+(romTable[1`,10]//2-romTable[A_Index`,10]//2)))`nromTable[A_Index`,7] := mgH - mgYOffset`nGdip_DrawImage(G1`, romTable[A_Index`, 13]`, romTable[A_Index`,6]`, mgH - mgYOffset`, romTable[1`,10]`, romTable[A_Index`,11]`, 0`, 0`, romTable[1`,10]//mgImageAdjust`, romTable[A_Index`,11]//mgImageAdjust)`nGdip_TextToGraphics(G1`, romTable[A_Index`,4]`, ""x"" . imageXcurrent . "" y"" . mgH-mgYOffset-mgText2Offset . "" "" . mgText2Options`, mgFont`, romTable[1`,10]`, romTable[A_Index`,11])`nmgArt%A_Index%X := imageXcurrent`nIf ( A_index <= paddingSpotsNeeded )`nimageXcurrent:=imageXcurrent+ romTable[1`,10]+imageSpacing`n}`n`nUpdateLayeredWindow(hwnd1`, hdc1`, 0`, 0`, mgW`, mgH)`nSetTimer`,Update`,30`n`nHotkey`,IfWinActive`,Layer ahk_class AutoHotkeyGUI`nHotkey`,UP`,Forward`nHotkey`,Down`,Backward`nHotkey`,Left`,Forward`nHotkey`,Right`,Backward`nHotkey`,%mgSelectKey%`,SelectGame`nHotkey`,%mgExitKey%`,MGCancel`nHotkey`,LButton`,MouseBlank`nHotkey`,RButton`,MouseBlank`nHotkey`,MButton`,MouseBlank`nReturn`n`nForward:`nIf (mgUseSound=""true"")`nSoundBeep`,%mgSoundfreq%`,10`nIf (mgSelectedEffect = ""grow"") {`nGdip_GraphicsClear(G2)`nmgGrowing:=`nb := 1`n}`nangle:=0`nold_currentButton:=currentButton`nIf (currentButton>1)`ncurrentButton:=currentButton-1`nElse`ncurrentButton:=romTable.MaxIndex()`nReturn`n`nBackward:`nIf (mgUseSound=""true"")`nSoundBeep`,%mgSoundfreq%`,10`nIf (mgSelectedEffect = ""grow"") {`nGdip_GraphicsClear(G2)`nmgGrowing:=`nb := 1`n}`nangle:=0`nold_currentButton:=currentButton`nIf (currentButton<romTable.MaxIndex())`ncurrentButton:=currentButton+1`nElse`ncurrentButton:=1`nReturn`n`nMouseBlank:`nReturn`n`nUpdate:`nIfWinNotActive`,Layer2 ahk_class AutoHotkeyGUI`nWinActivate`,Layer2 ahk_class AutoHotkeyGUI`nGdip_GraphicsClear(G2)`nIf (mgSelectedEffect = ""rotate"" && romTable[currentButton`, 12]) {`nangle := (angle > 360) ? 2 : angle+2`nGdip_ResetWorldTransform(G2)`nGdip_TranslateWorldTransform(G2`, mgRW%currentButton%//2`, mgRH%currentButton%//2)`nGdip_RotateWorldTransform(G2`, angle)`nGdip_TranslateWorldTransform(G2`, -mgRW%currentButton%//2`, -mgRH%currentButton%//2)`nGdip_DrawImage(G2`, romTable[currentButton`, 13]`, (mgRW%currentButton%-romTable[currentButton`, 10])`, (mgRH%currentButton%-romTable[currentButton`, 11])`, romTable[currentButton`, 10]`, romTable[currentButton`, 11])`nUpdateLayeredWindow(hwnd2`, hdc2`, romTable[currentButton`, 6]-1`, romTable[currentButton`, 7]-1`, mgRW%currentButton%`, mgRH%currentButton%)`nReturn`n} Else If (mgSelectedEffect = ""rotate"" && !romTable[currentButton`, 12]) {`nGdip_ResetWorldTransform(G2)`nGdip_DrawImage(G2`, romTable[currentButton`, 14]`, romTable[currentButton`, 6]`,  romTable[currentButton`, 7]`, romTable[currentButton`,10]`, romTable[currentButton`,11]`, 0`, 0`, romTable[currentButton`,10]//mgImageAdjust`, romTable[currentButton`,11]//mgImageAdjust)`n} Else If (mgSelectedEffect = ""grow"") {`nSleep`, 5`nIf !mgGrowing`nSetTimer`, MGGrow`, -1`nReturn`n}`nUpdateLayeredWindow(hwnd2`, hdc2`, 0`, 0`, mgW`, mgH)`nReturn`n`nMGGrow:`nmgGrowing:=1`nWhile b <= 30 {`nGdip_DrawImage(G2`, (If romTable[currentButton`, 12] ? (romTable[currentButton`, 13]):(romTable[currentButton`, 14]))`, romTable[currentButton`,6]-(b//2)`,  romTable[currentButton`,7]-(b//2)`, romTable[currentButton`,10]+b`, romTable[currentButton`,11]+b`, 0`, 0`, romTable[currentButton`,10]//mgImageAdjust`, romTable[currentButton`,11]//mgImageAdjust)`nUpdateLayeredWindow(hwnd2`, hdc2`, 0`, 0`, mgW`, mgH)`nb+=2`n}`nReturn`n`nSelectGame:`nSetTimer`,Update`, Off`nIf mgExitEffect {`nv := 1`nb+=2`nIf mgSelectedEffect = rotate`n{`nGdip_GraphicsClear(G2)`nGdip_ResetWorldTransform(G2)`nUpdateLayeredWindow(hwnd2`, hdc2`, 0`, 0`, mgW`, mgH)`n}`nLoop`, 25 {`nIf mgExitEffect = pixelate`n{`nmgArtOut := Gdip_CreateBitmap(romTable[currentButton`, 10]//mgImageAdjust`, romTable[currentButton`, 11]//mgImageAdjust)`nIf romTable[currentButton`, 12] {`nGdip_PixelateBitmap(romTable[currentButton`, 13]`, mgArtOut`,++v)`nGdip_DrawImage(G2`, mgArtOut`, romTable[currentButton`, 6]-(b//2)`, romTable[currentButton`, 7]-(b//2)`, romTable[currentButton`, 10]+b`, romTable[currentButton`, 11]+`n} Else {`nGdip_PixelateBitmap(romTable[currentButton`, 14]`, mgArtOut`,++v)`nGdip_DrawImage(G2`, mgArtOut`, romTable[currentButton`, 6]`, romTable[currentButton`, 7]`, romTable[currentButton`, 10]`, romTable[currentButton`, 11]`, 0`, 0`, romTable[currentButton`, 10]//mgImageAdjust`, romTable[currentButton`, 11]//mgImageAdjust)`n}`n} Else If mgExitEffect = grow`n{`nGdip_DrawImage(G2`, (If romTable[currentButton`, 12] ? (romTable[currentButton`, 13]):(romTable[currentButton`, 14]))`, romTable[currentButton`, 6]-(b//2)-(v//2)`, romTable[currentButton`, 7]-(b//2)-(v//2)`, romTable[currentButton`, 10]+b+v`, romTable[currentButton`, 11]+b+v`, 0`, 0`, romTable[currentButton`, 10]//mgImageAdjust`, romTable[currentButton`, 11]//mgImageAdjust)`n}`nUpdateLayeredWindow(hwnd2`, hdc2)`nv+=2`n}`n}`nselectedRom:=romTable[currentButton`,1]`nSplitPath`, selectedRom`,`,mgRomPath`,mgRomExt`,mgRomName`nIf romNeeds7z {`nmgRomExt:=""."" . mgRomExt`n7z%currentButton% := 7z(mgRomPath`, mgRomName`, mgRomExt`, 7zExtractDir)`nromTable[currentButton`,15]:=mgRomPath . mgRomName`n}`nGoto`, MGExit`n`nMGCancel:`nmgCancel:=1`nMGExit:`nHotkey`, IfWinActive`nSetTimer`,Update`, Off`nToolTip`nGdip_DeleteBrush(pBrush)`nfor index`, element in romTable`nGdip_DisposeImage(romTable[currentButton`,13])`, Gdip_DisposeImage(romTable[currentButton`,14])`nIf mgExitEffect = pixelate`nGdip_DisposeImage(mgArtOut)`nLoop`, 2 {`nSelectObject(hdc%A_Index%`, obm%A_Index%)`, DeleteObject(hbm%A_Index%)`, DeleteDC(hdc%A_Index%)`nGui`, %A_Index%: Destroy`n}`nGdip_Shutdown(pToken)`nSleep`, 1000`nHotkey`, %exitEmulatorKey%`, CloseProcess`, On`nHotkey`, %mgKey%`, StartMulti`, On`nGoto`, MultiGame`nReturn`n`nCreateRomTable(rom) {`nGlobal romPathFromIni`nGlobal romName`nGlobal romExtensionOrig`nGlobal 7zEnable`nromCount:=0`nromTable:=[]`ntypeArray := [""(Cart""`,""(Disc""`,""(Disk""`,""(Tape""]`nregExCheck = \s\(Disc\s[^/]*|\s\(Disk\s[^/]*|\s\(Cart\s[^/]*|\s\(Tape\s[^/]*`nromNamePre:=RegExReplace(romName`, regExCheck)`nLoop % typeArray.MaxIndex()`nIf rom contains % typeArray[A_Index]`n{`nLoop`, % romPathFromIni . romNamePre . A_Space . typeArray[A_Index] . ""*""`, 1`,1`n{`nIf romExtensionOrig contains % A_LoopFileExt`n{`nromCount+=1`nromTable[romCount`,1]:=A_LoopFileFullPath`nromTable[romCount`,2]:=A_LoopFileName`nromTable[romCount`,3] := RegExReplace(romTable[romCount`, 2]`, ""\..*"")`npos := RegExMatch(romTable[romCount`,2]`, regExCheck)`nuncleanTxt:= SubStr(romTable[romCount`,2]`, pos + 1)`nromTable[romCount`,4] := RegExReplace(uncleanTxt`, ""\(|\)|\..*"")`nromTable[romCount`,5] := SubStr(romTable[romCount`,4]`,1`,4)`n}`n}`n}`nReturn romTable`n}"

; Add CheckFile and ScriptError functions for the modules that use them.
retStr .= "`n`nCheckFile(file`,msg=""""`,timeout=6){`nIfNotExist`, %file%`n{`nIf msg`nScriptError(msg`, timeout)`nElse`nScriptError(""Cannot find "" . file`, timeout) `n}`nReturn %file%`n}"
retStr .= "`n`nScriptError(error`,timeout=6){`nMsgBox`,48`,Error`,%error%`,%timeout%`nExitApp`n}"

Log("Finished injecting functions into module")

If debugModule = 1
{
	Gui, 2:+Resize
	Gui, 2:+owner
	Gui +Disabled
	Gui, 2:Add, edit,r27 w585 readonly -E0x200, %retStr%
	Gui, 2:Add, Button, Default, OK
	Gui, 2:Show
	Gui, 2:Show, Center h400 w600, Debug Module
	Pause
}

Return retStr
}

2ButtonOK:
Gui, 1:-Disabled
Gui, 2:Destroy
Pause
Return

CheckFile(file,msg="",timeout=6){
IfNotExist, %file%
{
	If msg
		ScriptError(msg, timeout)
	Else
		ScriptError("Cannot find " . file, timeout)
}
Return %file%
}

ScriptError(error,timeout=6){
MsgBox,48,Error,%error%,%timeout%
Log(error)
ExitScript()
}

checkPaths(){
Global executable
Global romPath
Global emuPath
Global romExtensions
Global romExtension
Global systemName
Global romName
Global 7zExtractDir
Global 7zEnable
Global rarExtractDir
Global rarEnable
Global keymapperEnabled
Global keymapperProfilePath

Log("Checking paths")
romFound = 
StringRight, emuPathBackSlash, emuPath, 1
StringRight, romPathBackSlash, romPath, 1
StringRight, 7zExtractDirBackSlash, 7zExtractDir, 1
StringRight, rarExtractDirBackSlash, rarExtractDir, 1
StringRight, keymapperProfilePathBackSlash, keymapperProfilePath, 1

If (emuPath = "")
	ScriptError("Missing path in ini.")

If (emuPathBackSlash != "\" || romPathBackSlash != "\") || (7zEnable = "true" && 7zExtractDirBackSlash != "\" ) || (keymapperEnabled = "true" && keymapperProfilePathBackSlash != "\" )
	ScriptError("Make sure your paths contains a backslash on the end.")

If (emuPathBackSlash != "\" || romPathBackSlash != "\") || (rarEnable = "true" && rarExtractDirBackSlash != "\" ) || (keymapperEnabled = "true" && keymapperProfilePathBackSlash != "\" )
	ScriptError("Make sure your paths contains a backslash on the end.")

If (executable = "") 
	ScriptError("Missing executable in ini.")

If (romPath = "") 
	ScriptError("Missing rompath in ini.")

If (romExtensions = "")
	ScriptError("Missing rom extension in ini.")

If ( 7zEnable = "true" ) {
	checkFile(A_ScriptDir . "\7z.exe")
	checkFile(A_ScriptDir . "\7z.dll")
}
If ( rarEnable = "true" ) {
	checkFile(A_ScriptDir . "\unrar.exe")
}

checkFile(emuPath . executable)

If (systemName != "zinc"){
	Loop, parse, romExtensions, `,
	{
		inputVar = %A_LoopField%
		StringLeft, charToCheck, inputVar, 1
		If (charToCheck = ".")
		ScriptError("Make sure your rom extensions do not contain a .")

		IfExist %romPath%%romName%.%A_LoopField%
		{
			romExtension = .%A_LoopField% 
			romFound = true
			break
		}Else{
			IfExist %romPath%%romName%\%romName%.%A_LoopField%
			{
				romPath = %romPath%%romName%\
				romExtension = .%A_LoopField% 
				romFound = true
				break	   
			}Else{
				romFound = false
			}
		}
	}

	If ( 7zExtractDir = "" && 7zEnable = "true" )
		ScriptError("You are asking 7z to extract your ROMs. Your ROM's extension is " . romExtension . "`, but you did not specifiy a 7zExtractDir in the '" . systemName . ".ini' to extract to.")

	If ( rarExtractDir = "" && rarEnable = "true" )
		ScriptError("You are asking UNRAR to extract your ROMs. Your ROM's extension is " . romExtension . "`, but you did not specifiy a rarExtractDir in the '" . systemName . ".ini' to extract to.")
}

If (romFound = "false")
{
	If (systemName != "daphne"){
		ScriptError("Cannot find Rom - " . romPath . romName . " with any provided extension")
	}Else{
		ScriptError("Cannot find Daphne framefile - " . romPath . romName . " with any provided extension")
	}
}
Return romExtension
}

GetExtensions(){
Global romExtensions
Global romPath
Global romExtensions
Global romName
Log("Getting extensions")
Loop, parse, romExtensions, `,
{
	inputVar = %A_LoopField%
	StringLeft, charToCheck, inputVar, 1
	If (charToCheck = ".")
	ScriptError("Make sure your rom extensions do not contain a .")

	IfExist %romPath%%romName%.%A_LoopField%
	{
		romExtension = .%A_LoopField% 
		romFound = true
		break
	}Else{
		IfExist %romPath%%romName%\%romName%.%A_LoopField%
		{
			romPath = %romPath%%romName%\
			romExtension = .%A_LoopField% 
			romFound = true
			break	   
		}Else{
			romFound = false
		}
	}
}
Return romExtension
}

GetSystems(){
Static systemName
Static systems
Static ArrayCount = 1
Global lastSystem

systemsFile := checkFile(A_ScriptDir . "\Databases\Main Menu\Main Menu.xml")
Loop, read, %systemsFile%
{   
	pos := RegExMatch(A_LoopReadLine,"name=""(.*)""", SubPat)
	If (pos > 1){
		systems%ArrayCount% := SubPat1
		ArrayCount += 1
	}
}
ArrayCount -= 1

If (lastSystem != ""){
	elements := lastSystem . "||"
}Else{
	elements := "||"
}

Loop %ArrayCount%
{
	elements .= systems%A_Index% . "|"
}  

Gui, Add, ComboBox, x12 y100 w266 vEdit1, %elements%
}

GetFullName( fn ) {
; http://msdn.microsoft.com/en-us/library/Aa364963
; msgbox, %fn%
Static buf, i
If !i
	i := VarSetCapacity(buf, 512)
; msgbox, %buf%
DllCall("GetFullPathNameA", "str", fn, "uint", 512, "str", buf, "str*", 0)
; msgbox, %buf%
Return buf
}

SystemCursor(OnOff=1)   ; INIT = "I","Init"; OFF = 0,"Off"; TOGGLE = -1,"T","Toggle"; ON = others
{
Static AndMask, XorMask, $, h_cursor
	,c0,c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13 ; system cursors
	, b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13   ; blank cursors
	, h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11,h12,h13   ; handles of default cursors
If (OnOff = "Init" or OnOff = "I" or $ = "")	   ; init when requested or at first call
{
	$ = h	; active default cursors
	VarSetCapacity( h_cursor,4444, 1 )
	VarSetCapacity( AndMask, 32*4, 0xFF )
	VarSetCapacity( XorMask, 32*4, 0 )
	system_cursors = 32512,32513,32514,32515,32516,32642,32643,32644,32645,32646,32648,32649,32650
	StringSplit c, system_cursors, `,
	Loop %c0%
	{
		h_cursor   := DllCall( "LoadCursor", "uint",0, "uint",c%A_Index% )
		h%A_Index% := DllCall( "CopyImage",  "uint",h_cursor, "uint",2, "int",0, "int",0, "uint",0 )
		b%A_Index% := DllCall("CreateCursor","uint",0, "int",0, "int",0
			, "int",32, "int",32, "uint",&AndMask, "uint",&XorMask )
	}
}
If (OnOff = 0 or OnOff = "Off" or $ = "h" and (OnOff < 0 or OnOff = "Toggle" or OnOff = "T"))
	$ = b	; use blank cursors
Else
	$ = h	; use the saved cursors

Loop %c0%
{
	h_cursor := DllCall( "CopyImage", "uint",%$%%A_Index%, "uint",2, "int",0, "int",0, "uint",0 )
	DllCall( "SetSystemCursor", "uint",h_cursor, "uint",c%A_Index% )
}
}


LoadKeyMapper(byref MScript) {
Global
; msgbox, LoadKeyMapper Function`nkeymapper=%keymapper%`nhyperspinProfile=%hyperspinProfile%`nkeymapperExe=%keymapperExe%`nkeymapperPath=%keymapperPath%
; Build profile
If (keymapper="xpadder")
	hyperspinProfile := hyperspinProfile . ".xpadderprofile", defaultProfile := defaultProfile . ".xpadderprofile", systemProfile := systemProfile . ".xpadderprofile", romProfile := romProfile . ".xpadderprofile"
Else If (keymapper="joytokey")
	hyperspinProfile := hyperspinProfile . ".cfg", defaultProfile := defaultProfile . ".cfg", systemProfile := systemProfile . ".cfg", romProfile := romProfile . ".cfg"
Else If (keymapper="ahk")
	hyperspinProfile := hyperspinProfile . ".ahk", defaultProfile := defaultProfile . ".ahk", systemProfile := systemProfile . ".ahk", romProfile := romProfile . ".ahk"
Else
	ScriptError("Keymapper support is enabled`, but you set keymapper to """ . keymapper . """ which is not a valid option.")

If (FileExist(romProfile))
	profileToUse=%romProfile%
Else If (FileExist(systemProfile))
	profileToUse=%systemProfile%
Else If (FileExist(defaultProfile))
	profileToUse=%defaultProfile%
Else If (FileExist(hyperspinProfile))
	profileToUse=%hyperspinProfile%
Else
	ScriptError("Keymapper support is enabled for """ . keymapper . """`, but could not find a valid HyperSpin`, default`, " . systemName . "`, or " . romName . " profile in " . keymapperProfilePath . ".")

Log("Launching " . keymapper . " and first profile found = " . profileToUse)

; Launch keymapper
If (keymapper="xpadder") {
	SplitPath, profileToUse,, profileDir, profileExt, profileName ; need to splitpath again so we can find profiles for player 2+
	arProfileNames = | [p2]| [p3]| [p4]
	Loop, Parse, arProfileNames, |
	{
		If (FileExist(profileDir . "\" . profileName . A_LoopField . "." . profileExt))
			profile%A_Index% = %profileDir%\%profileName%%A_LoopField%.%profileExt%
	}
	RunXpadder(profile1,profile2,profile3,profile4)
} Else If (keymapper="joytokey") {
	IniRead, exitMeansMinimize, %keymapperPath%\JoyToKey.ini, LastStatus, ExitMeansMinimize ; checking if user has this option disabled, otherwise joytokey will not close with WinClose
	If ( exitMeansMinimize = "ERROR" )
		ScriptError("You are using KeyMapper support but are not up-to-date with JoyToKey or cannot find JoyToKey.ini in " . keymapperPath . "`nPlease make sure you are running JoyToKey v5.1.0 or later",10)
	Else If ( exitMeansMinimize = 1 ) {
		Process, Close, %keymapperExe% ; forcing JoyToKey closed because we need it running with the above option disabled to function properly
		Process, WaitClose, %keymapperExe% ; Make sure it's actually closed before continuing
		IniWrite, 0, %keymapperPath%\JoyToKey.ini, LastStatus, ExitMeansMinimize ; disabling this setting for user
	}
	WinClose, JoyToKey ahk_class TMainForm
	Process, WaitClose, %keymapperExe%,1 ; Make sure it's actually closed before continuing
	If ErrorLevel
		Process, Close, %keymapperExe% ; user possibly re-enabled the above option, closing it to continue script
	Log("Run, " . keymapperExe .  " """ . profileToUse . """, " . keymapperPath)
	Run, %keymapperExe% "%profileToUse%", %keymapperPath% ; Run joytokey
} Else If (keymapper="ahk") {
	Loop, Read, %profileToUse% ; Adding ahk remaps to the bottom of our module
		MScript .= "`n" . A_LoopReadLine
	; msgbox, %MScript%
}
Return hyperspinProfile
}

RunXpadder(profile1,profile2="",profile3="",profile4="") {
Global keymapperExe
Global keymapperPath
Log("Run, " . keymapperExe .  " """ . profile1 . """ """ . profile2 . """ """ . profile3 . """ """ . profile4 . """ /M, " . keymapperPath)
Run, %keymapperExe% "%profile1%" "%profile2%" "%profile3%" "%profile4%" /M, %keymapperPath%
}

BuildAhkRemap(profiles) {
Static retAhk
; moduleFile := checkFile(A_ScriptDir . "\Modules\" . moduleName . "\" . moduleName . ".ahk")
Loop, Parse, profiles, | ; Reading each profile, one at a time
{
	Loop, Read, %A_LoopField% ; Building ahk remaps into one big script
	{
		retAhk .= "`n" . A_LoopReadLine
	}
}
}

UnloadKeyMapper() {
;Unload keymapper or load HyperSpin profile if it exists
Global
Log("Unloading " . keymapper)
If (keymapper="xpadder") {
	If (FileExist(hyperspinProfile)) {
		SplitPath, hyperspinProfile,, hDir, hExt, hName ; need to splitpath again so we can find profiles for player 2+
		arProfileNames = | [p2]| [p3]| [p4]
		Loop, Parse, arProfileNames, |
		{
			If (FileExist(hDir . "\" . hName . A_LoopField . "." . hExt))
				hProfile%A_Index% = %hDir%\%hName%%A_LoopField%.%hExt%
		}
		RunXpadder(hProfile1,hProfile2,hProfile3,hProfile4)
	} Else {
		Log("Run, " . keymapperExe .  " /C, " . keymapperPath)
		Run, %keymapperExe% /C, %keymapperPath% ; or close if HyperSpin profile doesn't exist
	}
} Else If (keymapper="joytokey") {
	If (FileExist(hyperspinProfile)){
		WinClose, JoyToKey ahk_class TMainForm
		Process, WaitClose, %keymapperExe% ; Make sure it's actually closed before continuing
		Log("Run, " . keymapperExe .  " """ . hyperspinProfile . ".cfg"", " . keymapperPath)
		Run, %keymapperExe% "%hyperspinProfile%.cfg", %keymapperPath% ; Load HyperSpin profile
	}Else{
		DetectHiddenWindows, On
		WinClose, JoyToKey ahk_class TMainForm ; or close if HyperSpin profile doesn't exist
	}
}
}

Log(text,state="") {
FormatTime, logTime,, hh:mm:ss tt |%A_Space%%A_Space%
Global logFile
If state
	FileAppend, %text%`n, %logFile%
Else
	FileAppend, %logTime%%text%`n, %logFile%
}

IniReadCheck(file,section,key,defaultvalue="") {
IniRead, inivar, %file%, %section%, %key%
If ( inivar = "ERROR" ) {
	IniWrite, %defaultvalue%, %file%, %section%, %key%
	Return defaultvalue
}
Return iniVar
}

CreateGlobalFile: ; ********REMOVE THIS ONCE HS2 IS OUT****************
iniMigrate =
( ltrim c
   HyperLaunch, Hide_Cursor, false
   HyperLaunch, Fade_In, false
   HyperLaunch, Fade_Out, false
   HyperLaunch, Fade_Color, 0x000000
   HyperLaunch, Fade_In_Duration, 500
   HyperLaunch, Fade_Out_Duration, 500
   HyperLaunch, Fade_In_Delay, 0
   HyperLaunch, Keymapper_Enabled, false
   HyperLaunch, Keymapper, %A_Space%
)
Loop, Parse, iniMigrate, `n
{
	StringSplit, split, A_LoopField, `,, %A_Space%%A_Tab%
	IniRead, tempVar, %settingsFile%, %split1%, %split2%
	If % tempVar!="ERROR" ; if user has this setting, let's write it to the global ini
		IniWrite, % tempVar, %globalFile%, %split1%, %split2%
	If % tempVar="ERROR" ; if user never set this this setting, let's write the default to the global ini
		IniWrite, % split3, %globalFile%, %split1%, %split2%
}
Return


ToggleCursor:
SystemCursor("Toggle")
Return

GuiClose:
ExitScript()

ExitScript:
Log("User pressed exit_script_key")
ExitScript()
Return 

ExitScript() {
Global keymapperEnabled
Global hideTaskbar
If (hideTaskbar = "true"){
	Log("Unhiding taskbar")
	WinShow, ahk_class Shell_TrayWnd
	WinShow, ahk_class Button
}
If (keymapperEnabled = "true" )
	UnloadKeyMapper()
Process, Exist, HyperSpin.exe
PID := errorLevel
If (PID) {
	WinActivate, ahk_pid %PID%
	WinWaitActive, ahk_pid %PID%
}
SendMessage,0x112,0xF170,-1,,Program Manager
SystemCursor("On")
;Emergency restore cursor, just in case something goes wrong
SPI_SETCURSORS := 0x57
DllCall( "SystemParametersInfo", UInt,SPI_SETCURSORS, UInt,0, UInt,0, UInt,0 )
Log("

","end")

ExitApp

}

[/code]

I uploaded the exe to the ftp for all those interested as well as the unrar.exe needed (free to distribute) :-D

This works JUST like 7z in that you need to add/edit all the same lines but with rar.

i.e. You will need to add the following line to any module you want to have rar support:

rar1 := rar(romPath, romName, romExtension, rarExtractDir)

rar2 := rarCleanUp()

add it right after where the 7z line exists.

You will also have to modify the following in your global settings ini

rar_Enabled=true

rar_Extract_Dir= whatever you want it to be.

That being said... IT WORKS. If you're interested - try it.

rar_Delete_Temp=true

Posted

thanks :-)

I might have spoken too soon, it pseudo works. I tried with a few 3do games and for some reason killing time and road rash will NOT work, it instead attempts to pass the file as .rar to the emulator directly instead of even trying to extract. Icebreaker, putt putt golf, and return fire I know work.

Might need a little more work, don't convert everything yet...

Posted

nope, I didn't speak too soon... works just fine.

I was testing with rar files that had different names from the archives inside like a dummy.

Loading happens blindingly fast an everything runs great.

I think I might be recompressing my iso collections after some more testing.

Posted

I just wanted to mention here in this thread that I did NOT mess with the multigame support whatsoever, that is the longest line of code it's crazy. This works for single game rar files but they do NOT have multigame support so everyone is aware before converting what they have or making big changes.

testing still works without a hitch and I am prettymuch sold on rar5.

I don't see myself attacking mg support so I will probably leave this for anyone else to pick up on if they feel so adventurous.

Posted

Ha!

I will never be great at ahk I am a terrible coder, I am just analytical enough to program my way out of a wet paper bag. The code for multigame is not wet paper bag enough for me.

JLyWL.jpg

  • 4 weeks later...
Posted

Hi,

I'm just a random guy from the internet but i want to say thank you for you comparison and tests. I searching rar5 vs 7zip and find only this. Vell done. WinRAR FTW!

  • 1 month later...
Posted

But that's no guarantee that 7z decompressing rar5 will be fast. Integrating rar5 support into HyperLaunch is far more plausible at this point.

Posted
Integrating rar5 support into HyperLaunch is far more plausible at this point.

+1

When I look at the 7zip open tickets I cannot agree more:

# open tickets: 1061

# closed tickets: 101

Before 7zip can support Rar5 files, it first needs to support Multi-Core CPUs.

Posted

damn,

You might be right. I know that RL has a LOT of hooks into the api for 7z so I don't expect djvj to dedicate the time to this. That's too bad I would love the speed too. 4 minute load times on a 4 gig iso kinda suck.

  • 4 months later...
Posted

this tests are very superficials...

if i want speed creating 7z files you just change this settings:

compression level: Fastest

compression method: lzma2

i get a litte bit more compression and it's faster than rar5 with the best compression method

Folder: $oem$	files: 1.806 sub-folders: 229  size 193 MB

7z settings:
compression level: Fastest
compression method: lzma2
the rest untouch

winrar 5.01 rar5 settings:
compression level: The Best
dictionary size: 32MB

Packing:
7z              00:00:07     159.325 KB
rar5.01        00:00:20     160.529 KB

Unpacking:
7z              00:00:12
rar5.01       00:00:07

Just unpaking rar5 is a little bit faster wich is not a real problem

folder source: http://www.sockshare.com/file/E73190645628F422

Posted

Hi and welcome to HyperSpin forums!

Let me begin by saying that my tests are NOT superficial...and I will prove it.

By the way, I unpacked your test folder and it has a total size of 198 MB... however 179MB of it are jpg files! Not the best source for comparing 2 compressing programs since jpg format is already a compressed format! I prefer to do my test with a GameCube game. After all, my main goal is to unpacked well compressed game images the fastest as possible.

So here are my results:

Test file: "Legend of Zelda, The - The Wind Waker (USA).iso" 1.35 GB (1,459,978,240 bytes)

7z default settings:

Packing - 3m13s -> 1.05 GB (1,133,869,160 bytes)

Unpack - 1m11s

7z + LZMA2 -NORMAL settings:

Packing - 1m47s 7zip packing 1.05 GB (1,131,568,693 bytes)

Unpack - 0:48s

7z + LZMA2 -FASTEST settings: (your recommended settings)

Packing - 46s 7zip packing 1.14 GB (1,229,921,970 bytes)

Unpack - 0:54s

RAR5 Default settings:

Packing - 1m55 1.07GB 1.149.296.568 bytes)

Unpack - 0:08s

RAR5 FASTEST settings:

Packing - 0:20s 1.12 GB 1,203,159,684 bytes)

Unpack - 0:07s

Do I really have to comment the rar5 results ? The unpacking speeds are not just "a bit faster" like you think. 7s VS 48s is a huge difference! In this test and all my other "unpacking" tests were similar to this one. WinRar5 clearly explodes 7zip. This is a fact and NOT superficial.

It is sometimes true that 7z compresses better than the rar5 does but the difference is often minimal. (in this test 1.07 GB for rar5 VS 1.05 GB for 7z)

What can we say about your settings?

The 7z default settings use the compression method LZMA, which is limited to 2 CPU threads while the one you suggest (LZMA2 compression method) use 4 threads. So users with 4 Core CPUs should definitely switch to LZMA2 compression method. This will speed the compression process for the same end size. Thanks for that.

Using the compression level "FASTEST" does pack the files faster but then you get poor compression results (worst compression result in this test). Switch the setting to "NORMAL" gets you better compression but slower performance in packing.

Up to you depending what you really look for.

Thanks for reading and testing.

Posted

Why bother compressing ISO files? Seriously. Just buy a bunch of 4TB hard drives and be done with it. Sitting here discussing compression to save yourself up to say a TB of drive space over a possible max of 24TB.. That TB of space costs under $100 and gets put into a cab that has set you back thousands and now that cab runs slow because you saved yourself $100. Well done. :P *sighs*

Posted
Why bother compressing ISO files? Seriously. Just buy a bunch of 4TB hard drives and be done with it. Sitting here discussing compression to save yourself up to say a TB of drive space over a possible max of 24TB.. That TB of space costs under $100 and gets put into a cab that has set you back thousands and now that cab runs slow because you saved yourself $100. Well done. *sighs*

lol i have to agree with you its pointless compressing everything and even then why would you want every single cd based game some dont work or have issues running through the emu or just some games are just plain crap if your gonna include disc based systems you should only include games worth playing.

Posted

Wrong hobby...lol

So you're saying there's really no point in discussing compression when we could all just go out and just buy more hard drive space. I agree but managing the space that you have on your hard drive more effectively is something that I was very impressed with when RL came out.

I've also wanted to question, "Is HyperSpin all about people that can afford and build arcade cabinets?"

You can just look at the HyperSpin setup and tell it's supposed to be used on a cab. Thousands of dollars?? I wish I could lie and say I had one of those. Minimizing a hard drive cost is easy at the cost of a thousand dollar cab then.

Zero Dreams is using an old Samsung lcd from 5 years ago. The only one in the entire tiny house. My PC I posted here (before I got it). I say all of this to say: "Yes, compression is important because it saves space. Space costs money which is hard for some of us to get. Decompressing these files is important to discuss because it takes a while to load these iso's."

For me personally, I would like to have my isolated images compressed on my backup drives but just the raw images on my primary drives loaded when I launch the game so there is no loading time. Gotta wait for my tax check though. :P

*I know I'm not the only guy with no cab who uses HS

**My bad for yet another rant

Posted

Wish I was a teenager living at home with Mom and Dad again and had no responsibilities. Some of us adults don't have money falling out our asses and in order to run what we want we do need compression. This thread is certainly worth considering. There appears to be benefits to this. Even if people want to argue the "buy more space" aspect, did you dumb dumbs forget that most of the shit you download/ed is compressed? Did you stop to realize how much time and bandwidth that saves a person having smaller download sizes? Did you think about how many roms have to be unzipped, ran through a renamer?

This isn't much of a debate now is it?

Zero Dreams - you and I are in the same boat. Idea rich - money poor.

  • 4 months later...
Posted

Great job! It's very interesting. I made some tests, and RAR5 unpacking speed is awesome!

Is the some script compatible with RocketLauncher.x?

Posted

No, and most probably will never be. It is not that easy to support that in hyperlaunch for various reasons.

Besides that, any advance on these kind of things are usually catchup by other programs like 7z, so wasting our free time developing this is not a that good alternative as we do not have that much time available anyway.

If anyone wants to do this by themselves is another history. I am sure that any improvement made by any user will be included in hyperlaunch with almost no objections from djvj and brolly, as this was my exactly the case when I introduced to them the hyperpause test code that I made.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...