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

Ok here is the point: Most of my roms and CD based games are all 7zipped to save disc space. Now, the problem comes when you launch a GameCube, or PS2 game or any "big" CD game. It takes ages to uncompress by HL. I saw that the new HL2.0 has a nice loading bar when unzipping your game. This helps you to wait without asking yourself: "Is it still loading?" but waiting sometimes 1 to 2 minutes before you can play your PS2 game is simply too much...

I decided to look back to the old WinRar and learned today that WinRar 5 was beta and available to download. So I decided to give it a try and measure it against the previous WinRar version which is 4.20 and 7zip 9.20.

As you can see below, the time to uncompress WinRar 5 archives is simply amazing! Take the first example: 53 seconds to launch Alone in the Dark DreamCast if the iso is 7zipped. I takes only 7 seconds with WinRar 5 and 11 with WinRar 4.20. Now some people might say WinRar is faster but does not compress as well as 7zip. That was true with previous versions of WinRar. If you check my last test, you see that WinRar 5 compresses as well as 7zip 9.20.

For me WinRar 5 clearly beats 7zip because of it's great performance speed while keeping very efficient compression ratios.

On thing to pay attention though is that WinRar5 uses a new archive format and older WinRAR versions are not able to decompress RAR 5.0 archives. So if you plan to send an archive to other people, it is necessary to take the compatibility issue into consideration. You can select "RAR" instead of "RAR5" option in archiving dialog to create RAR 4.x archives compatible with previous WinRAR versions.

post-11587-142870589984_thumb.png

Here are the results: (I just picked some random CD games.)

(Tests done on a SATA3 HDD Core i5 Sandy Bridge 4 core 3.2Ghz)

7zip 9.20 64bit version used default settings.

WinRar 5.0 64bit default settings.

WinRar 4.20 bit default settings.

Alone in the Dark - The New Nightmare (USA) (Disc 1) (DreamCast)	size 1.187.717.813 MB
Packing:
7z            00:02:34     905.824.820
rar 4.XX       00:01:03     932.121.931
rar 5.00       00:01:32     924.654.458

UnPacking:
7z             00:00:53
rar 4.XX      00:00:11
rar 5.00      00:00:07

Sonic CD (Sega CD)	size 601.706.549 MB
Packing:
7z		00:01:17	424.546.648
rar 4.XX	00:00:23	364.100.327	
rar 5.00	00:00:38	380.030.452	

UnPacking:
7z		00:00:25
rar 4.XX	00:00:09
rar 5.00	00:00:03

Benefactor (Europe) (Amiga CD32) size 540.741.923MB (Many wav files)
Packing:
7z		00:01:16	480.432.284
rar 4.XX	00:00:22	392.473.687
rar 5.00	00:00:46	412.634.423

UnPacking:
7z		00:00:29
rar 4.XX	00:00:09
rar 5.00	00:00:03

Legend of Zelda, The - The Wind Waker (USA) (GamdCube)	size 1.459.978.240 MB
Packing:
7z		00:04:40	1.182.305.393
rar 4.XX	00:01:14	1.163.525.401
rar 5.00	00:01:49	1.149.296.570	

UnPacking:
7z		00:01:13
rar 4.XX	00:00:13
rar 5.00	00:00:09


Gran Turismo (USA) (v1.1) (PS)	size 693.668.395 MB
Packing:
7z		00:01:36	336.077.817	
rar 4.XX	00:00:29	377.142.907
rar 5.00	00:00:39	351.992.722

UnPacking:
7z		00:00:21
rar 4.XX	00:00:05
rar 5.00	00:00:03

Aa! Megami Sama - Disc A (NEC PCFX) size 496.107.286 MB
Packing:
7z 9.20         00:01:11        168.075.015		
rar 4.XX	00:00:23	339.255.824	
rar 5.00	00:00:22	168.636.757

UnPacking:
7z		00:00:11
rar 4.XX	00:00:04
rar 5.00	00:00:02

  • Replies 63
  • Created
  • Last Reply
Posted

Sounds interesting, I didn't even now the rom archives were or could be compressed, to be honest so I don't have anything useful to say except well, interesting.

Ow, haha, your country is smaller than mine! I don't get to say that a lot, lol. Must be better compressed :D

Posted

Well as you see everything is compressible. :) Some games depending their contents and their system compress better than others. I did not compress GameCube isos before because it took over a minute to decompress. Now with WinRar I just have to wait 9 seconds and save more or less 300MB disc space per game.

It would be great if HL2.0 could support WinRar 5. The problem I see is that every module will need to be updated because 7zip can't uncompress WinRar 5 files. ;( Maybe Djvj can confirm.

Posted

My first guess would be that it wouldn't either. If winrar 5 had a dll, it might be something I could look into. Those speed vs size comparisons are hard to ignore.

Posted

Thanks djvi!

There is an official dll for RAR5. You can get it here. http://www.rarlab.com/rar_add.htm

I already tested it in Nestopia which supports rar files. I replaced the dll by the new one and it opened rar5 archives. Now I couldn't test the performance but the read me file says: [...this library and RAR/UnRAR tools share

the same source code. So the latest version of unrar.dll usually contains same decompression algorithm changes as the latest UnRAR version.]

Got some time this 2 next weeks so let me know if need me to beta test this.

Posted

Thanks someone else gave me that link too. When I get some time I'll take a look. Probably not anytime soon though.

Sent from my Samsung Galaxy S3

Posted

How are you getting those speeds clocked?

I don't doubt the prowess or improvements to rar5 but I do find myself skeptical of a single sata 3 drive reading and then writing 1.5gb in 9 seconds.

1.5x2=3gb= 333 megabytes/second steady stream assuming 0 pause or wait for processing. This HAS to have been ssd it's physically impossible to get those speeds on a rotational platter drive.

now otherwise looking at this...

I will be keeping a keen eye on this thread and looking deeper to rar5. It looks like it supports a full command line function so while djvj doesn't have time to look at it now - I can see this in our future...

path_to_winrar:C:\program files (x96)\winrar\winrar.exe

...

Hell I might even play with it if I get some time.

Posted

ok I just downloaded rar5 and the source to HL2 off hyperlist. Man I remember poking around hl1 code and thought maybe I could bastardize something from the 7z code (I'm no programmer other than lame batch files) to make some hobble together function for winrar. Well now that I looked at it...

I don't quite think we thank djvj enough for what he does. That is just... CRAZY. Nothing like what I expected to see for that or any of the other complicated sub-routines like multigame support. I don't think I could half ass my way through this one with plagiarizing and luck anymore. I thought I had seen some complex ahk before but I cant even remotely follow that.

Posted

Yes I know, he works miracles. Everything is streamlined and works well. I'm not a coder, I just know that at the end of the day, the error log in my head turns out pages whilst HL always returns a clean sheet.

Posted

Actually for my tests above I was not only using a single HDD drive but 2 HDD. I decided to make more tests with single HDD, 2 HDD and SSD. I also decided to used a different PC with is a little older (Core i5 750 2,67Ghz, no SATA3).

The results are very interesting and may give you an answer to your math above. As you can see, the time to unpack the 7zip archive is pretty much the same. No matter if the destination drive is a HDD or a SSD. This test tells us that it is not the drive that is the bottleneck but more the algorithm that takes time to decode. In this case only CPU speed can make the decompression faster.

Now the time RAR5 archive took to decompress varied quite a lot. That simply tells us that the algorithm decodes the archive faster.

I also added a final test where I compress the game to 7z and then to RAR5. On a single hard drive, compressing Gran Turismo 4 to 7zip took over 16 minutes while with WinRAR5 it only took 8 minutes! I think the reason for this is that Winrar used my 4 CPU core to do its compression while 7zip only used 2 cores.

Still, again, WinRAR 5 is the winner.

I will do a final test with a GameCube again on this PC. Let's see how much time I get.

Gran Turismo 4 (PS2) size 5189 MB

Unpacking from HDD to same HDD (SATA2) drive:
7zip = 00:05:48
RAR5 = 00:02:07


Unpacking from HDD to different HDD (SATA2) drive:
7zip = 00:05:26
RAR5 = 00:01:18


Unpacking from HDD to SDD (SATA2) drive:
7zip = 00:05:26
RAR5 = 00:01:00




Packing from HDD to same HDD (SATA2) drive: 
7zip = 00:16:31   4206 MB
RAR5 = 00:08:27   4260 MB

Posted

I think I figured out a way to make this work with HL after some more reading. This is a COMPLETE bastardization mind you and includes none of his original error checks and additional foolproofing. Here is some proof of concept of what is in my head though.

Download the HL 2.25c source from hyperlist, look for the following line of code:

{`n7zExtractDir = %7zExtractDirCheck%`nRunWait`, %7zPath% x ""%7zP%%7zN%%7zE%"" -aoa -o""%7zExtractDir%"

unrar.exe does not respond to -aoa which is auto overwrite. It also does not use -o for output directory - you should be able to simply put the directory there.

Therefore I theorize you could rename unrar.exe to 7z.exe znd replace the original 7z.exe. Then replace the line "-aoa -o" with "-o+" in the script and re-compile.

-aoa auto overwrite

replace with -o+

-o output directory - un-neccesary.

unrar.exe is free to distribute and does not require a dll.

I think it will work I just cant for the life of me get ahk to compile a working hyperlaunch for me. I must have some weird versions, I will have to look and play with it later.

Posted

Thanks I might try that but I am pretty sure djvj is going to add WinRAR5 support without "bastardization". :) This is also my last test. There is nothing more to prove that RAR5 is awesome! 15 sec wait against almost 1 and half minute! for 7z :cool:

Mario Kart - Double Dash!! (USA) (GC) size  1230 MB

Packing: -> single SDD (SATA2 OCZ Vertex2) drive: 
7zip = 00:03:49
RAR5 = 00:02:10

Unpacking: -> single SDD (SATA2 OCZ Vertex2) drive: 
7zip = 00:01:25
RAR5 = 00:00:15

Posted

awesome, yea looks good.

I probably will do it just because I'm impatient and I am looking at recompressing my entire collection lately. I actually was JUST on the cusp of it funny enough. This thread makes me want to hold that thought.

Posted

ok for anyone curious, I tested and confirmed functionality.

Here is the full snippet of the 7z extract routine with the code I modified underlined in bold:

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 -ad -o+ ""%7zP%%7zN%%7zE%"" ""%7zExtractDir%""`,`,Hide`nIf ( ErrorLevel != 0 ) {`nIf ( ErrorLevel = 1 )`nError = Non fatal error`, file may be in use by another application`n

I have tested and confirmed full functionality with multiple game for different systems. Man this loads fast across the lan for me.

If you download unrar.exe and rename it to 7z putting it in the same dir as this recompiled hyperlaunch it works great as proof of concept. unrar however will ONLY decompress rar archives so by doing this it breaks everything else to prove it could work if we wanted. I am sure error message functionality is useless and would need to be re-created. Other than that I think it could be integrated by copying the 7z routine and tweaking it to be it's own routine for rar files only, breaking rar functionality off from the original 7z. this could co-exist easily. Re-creating modules is something I don't know is worth it, it would be cosmetic coding. The routine could be killed in global settings if someone didn't want rar5 functionality so the only reason to change modules would be because we didn't want it to say 7z.

I might dig into this more tomorrow, dunno. I keep saying later but here I am nearly 1am playing with this.

Posted

You can play around with it, but it's not going to mean much unless I add support for it in the new HL, which I make no guarantees atm because it might break fade from showing progress until our hyperlaunch.dll can support it.

Posted

djvj; how are you hooking the progress output from 7z? are you using 7zg in the new hl?

unrar.exe displays a progress bar at the command prompt (shown at bottom of my post) but 7z doesn't display one natively without using 7zg.exe?

C:\Hyperspin>unrar x -ad -o+ "G:\Console Gaming\Panasonic 3do\Games\Road rash (usa)

rar5.rar" "S:\working directory\hs\"

UNRAR 5.00 beta 3 freeware Copyright © 1993-2013 Alexander Roshal

Extracting from G:\Console Gaming\Panasonic 3do\Games\Road Rash (USA)rar5.rar

Creating S:\working directory\hs\Road Rash (USA)rar5 OK

Extracting S:\working directory\hs\Road Rash (USA)rar5\Road Rash (USA).iso

25%

Might be hard to catch progress since it's happening so damn fast ;-). Extracting that 656mb iso took 8 seconds even though I was pulling it across a samba share. I think I'm in love

Posted

tastyratz, have you seen this thread ? There's one video that shows the progress bar. I think what djvj means is that adding WinRar support might break this bar which was customize for 7zip. I am also not a coder but I think this bar will need to be recoded in order to work with unrar.dll or unrar.exe. It is sad that I have not posted this before dj started to work on the progress bar. On the other hand that does not mean it will never be added.

I am not sure a co-existence of the 2 archives is good solution. In my opinion WinRAR 5 decompresses 7zip archives so there is no need to keep 7zip library. If people prefer to keep their games 7zipped they can. The others like us who want to do this step their can.

Posted

We have our own HyperLaunch.dll which basically hooks into 7z.dll (the one you have now) and through a loop, we can read progress which gets translated into graphics on screen. Most isos and torrents are all 7z anyways, so it's not the biggest deal right now, but it is something that can be looked into going forward.

Posted

ok so the whole routine is way different now then you are.

I'm not worried about what's out there now as much as these drastic differences make cd image games playable out of an archive now. I am OK with losing the loading bar for the immediate term for just my cd games. I can wait I know it won't be a priority for you, getting RL out the door matters more than any new feature.

The more I play with it the more I think I want to convert everything I have to rar5. I might bastardize this more and try to make it co-exist as it's own routine. Then later when RL comes out worst case I can paste my hooks into it and make it work for rar5 till you get around to it.

Besides, I don't know dick about ahk but I am having fun as someone with 0 programming experience. I'm proud of myself for making it function even if I just stole and chopped your code up to make it happen. If I can't figure out splitting it to 2 routines... well I am no worse off.

Once I'm happy I will probably just drop it on the ftp in my folder to share, maybe I can help someone else out as excited as I am. If I get it working and end up happy with the results then I will probably take my existing collections and create new ones in rar5 to share so people have the option.

Posted

I'm guessing 7z will support winrar5 decompressing sooner or later so I wouldn't waste any time changing any code to support it for a while.

Posted

winrar 5 is still beta and only a few weeks old. 7z's last release was 2010 and shows a table against rar 3.5 on the homepage.

I don't think 7z is really actively being updated so much so that it will be something we see anytime soon.

I actually made some good progress on it. My change in the routine in the proof of concept above worked, now I just have to figure out how to split the existing 7z routine into it's own. I think I'm close but it isn't quite working yet.

If anyone is interested here is where I left off last (not working still experimenting), Ill be playing with it more tonight. I tried to put obnoxious tags to stick out where I did most of my changes to his code.

;-----------------------------------------------------------------------------------------------------------------------------------------
; 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 .= "`nrarExtractDirOrig = " . rarExtractDirOrig
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 . "" lawl """""" . 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_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`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]

djvj's priority right now is to get RL out the door but I am not really part of that so I wanted to play around with this. my hope is that if I can get this working then maybe I can paste my changes into RL when that comes out and have rar5 working just the same sans progress bar.

Posted

It's good for your own advancement to play with it, but sorry to say, this will never work in RL. The progress bar gets it's information through COM and an external HyperLaunch.dll.

Posted

I mean I can't just plug in those changes and expect it to work with fade. It will work with extracting fine, but thats it.

Posted

Winrar5 would be awesome if it was officially supported but I think I would use tastyratz version as 7zip takes soooo long to uncompress PS2 and Wii games.

Archived

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

×
×
  • Create New...