/*
This file is part of Universal USB Installer (UUI)
It is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with it. If not, see <https: www.gnu.org licenses/>.
Copyright https://pendrivelinux.com (See UUI-Copying.txt and UUI-Readme.txt for more information, Credits, and Licensing)

07/13/2026 - Universal-USB-Installer-2.0.3.8: Updated to use Ventoy version 1.1.16 bootloader, fixing boot issues with old UEFI version firmware when secure boot is disabled. Fixed a bug where prepare/update reported success on the wrong disk num, though the correct disk was prepared/updated.
*/

!define NAME "Universal USB Installer"
!define FILENAME "Universal-USB-Installer"
!define VERSION "2.0.3.8"
!define Ventoy_Version "1.1.16"
!define MUI_ICON "images\usbicon.ico"
!define MUI_CUSTOMFUNCTION_ABORT onUserAbort ; Custom Cancel

; MoreInfo Plugin - Adds Version Tab fields to Properties. Plugin created by onad https://nsis.sourceforge.net/MoreInfo_plug-in
VIProductVersion "${VERSION}"
VIAddVersionKey CompanyName "pendrivelinux.com"
VIAddVersionKey LegalCopyright "Copyright Pendrivelinux.com"
VIAddVersionKey FileVersion "${VERSION}"
VIAddVersionKey FileDescription "${NAME} : Software used to create a bootable USB drive"
VIAddVersionKey License "GPL Version 2"

Name "${NAME} ${VERSION}"
OutFile "Output\${FILENAME}-${VERSION}.exe"
RequestExecutionLevel admin ;highest
SetCompressor /SOLID lzma
CRCCheck On
;XPStyle on
ShowInstDetails show
BrandingText "${NAME} ${VERSION}"
CompletedText "All Finished, Process is Complete!"
InstallButtonText "Create"
Unicode True

!include TextFunc.nsh
!include WinVer.nsh
!include WordFunc.nsh
!include nsDialogs.nsh
!include MUI2.nsh
!include FileFunc.nsh
!include LogicLib.nsh
!addplugindir "plugins"

; Variables
Var preJustDrive
Var AccumDrives
Var SysDrive
Var RecentVersionDisplay
Var Wipe
Var VersionChk
Var Online_Version
Var Ventoy_Version
Var JsonPath
Var Capacity
Var VolName
Var Checker
Var FileFormat
Var Format
Var FormatMe
Var FormatChoice
Var BlockSize
Var Dialog
Var LabelDrivePage
Var Distro
Var DistroName
Var ISOFileName
Var DestDriveTxt
Var JustDrive
Var DestDrive
Var BootDir
Var LinuxDistroSelection
Var LabelISOSelection
Var ISOFileTxt
Var TheISO
Var IsoFile
Var ISOSelection
Var ISOTest
Var JustISO
Var JustISOName
Var JustISOPath
Var DestDisk
Var DownloadISO
Var DownloadMe
Var Link
Var Link2
Var Links
Var Links2
Var Auth
Var DownLink
Var LocalSelection
Var Letters
Var DistroPath
Var SomeFileExt
Var AllDriveOption
Var DisplayAll
Var DistroLink
Var Homepage
Var OfficialSite
Var OfficialName
Var NameThatISO
Var Uninstaller
Var Removal
Var InUnName
Var InUnStall
Var InUnStalling
Var InUnStalled
Var OnFrom
Var RepeatInstall
Var ShowAll
Var ForceShowAll
Var ShowingAll
Var SizeOfCasper
Var Casper
Var CasperSlider
Var CasperSelection
Var SlideSpot
Var CasperSelection1
Var CasperSlider1
Var SlideSpot1
Var CasperFile
Var CasperSizeText
Var CasperURL
Var NXT
Var BCK
Var ReUpdate
Var DrivePrepared
Var VTOY_LABEL
Var VTOY_GPT
Var VTOY_NOSB
Var VTOY_NONDEST
Var VTOY_RESERVE
Var VTOY_CONFIRM
Var VTOY_FS_LABEL
Var VTOY_RESERVE_LABEL
Var VTOY_GPT_STATE
Var VTOY_NOSB_STATE
Var VTOY_NONDEST_STATE
Var VTOY_FS_CTL
Var VTOY_FS_VAL
Var VTOY_RESERVE_VAL
Var VTOY_ARGS
Var VENTOY_ACTIVE
Var VTOY_INFO
Var RemainingSpace
Var Persistence
Var CasperName
Var COMSPEC
Var PERCENT
Var FSType
Var DiskNum
Var BOOT_DISK
Var INST_DISK
Var NEWSLUG
Var NEWCOMMENT
Var OLDCOMMENT
Var COMMENT
Var DELPERSIST
Var PersistName
Var PersistName2
Var VHDSize
Var VHDLBL
Var WINE
Var VHDDisk
Var LastValidDistroIndex

; Var declarations for drive variables (HDD0 to HDD26)
Var HDD0
Var HDD1
Var HDD2
Var HDD3
Var HDD4
Var HDD5
Var HDD6
Var HDD7
Var HDD8
Var HDD9
Var HDD10
Var HDD11
Var HDD12
Var HDD13
Var HDD14
Var HDD15
Var HDD16
Var HDD17
Var HDD18
Var HDD19
Var HDD20
Var HDD21
Var HDD22
Var HDD23
Var HDD24
Var HDD25
Var HDD26
Var Removable
Var WipeDiskpartScript

!include ReplaceInFile.nsh
!include DiskVoodoo.nsh

; Interface settings
!define MUI_FINISHPAGE_NOAUTOCLOSE
!define MUI_HEADERIMAGE
!define MUI_HEADERIMAGE_BITMAP "images\usb-logo-nsis.bmp"
!define MUI_HEADERIMAGE_BITMAP_NOSTRETCH
!define MUI_HEADERIMAGE_RIGHT

; License Agreement Page
!define MUI_TEXT_LICENSE_SUBTITLE $(License_Subtitle)
!define MUI_LICENSEPAGE_TEXT_TOP $(License_Text_Top)
!define MUI_LICENSEPAGE_TEXT_BOTTOM $(License_Text_Bottom)
!define MUI_PAGE_CUSTOMFUNCTION_PRE License_PreFunction
!insertmacro MUI_PAGE_LICENSE "UUI-Copying.txt"

; Distro Selection Page
Page custom SelectionsPage

; Install Files Page
!define MUI_INSTFILESPAGE_COLORS "00FF00 000000" ;Green and Black
!define MUI_INSTFILESPAGE_FINISHHEADER_TEXT $(Finish_Install)
!define MUI_TEXT_INSTALLING_TITLE $(Install_Title)
!define MUI_TEXT_INSTALLING_SUBTITLE $(Install_SubTitle)
!define MUI_TEXT_FINISH_SUBTITLE $(Install_Finish_Sucess)
!define MUI_PAGE_CUSTOMFUNCTION_PRE InstFiles_PreFunction
!insertmacro MUI_PAGE_INSTFILES

; Finish page
!define MUI_FINISHPAGE_TITLE $(Finish_Title)
!define MUI_FINISHPAGE_TEXT $(Finish_Text)
!define MUI_FINISHPAGE_LINK $(Finish_Link)
!define MUI_FINISHPAGE_LINK_LOCATION "https://pendrivelinux.com/universal-usb-installer-easy-as-1-2-3/"
!define MUI_WELCOMEFINISHPAGE_BITMAP "images\finish.bmp"
!define MUI_PAGE_CUSTOMFUNCTION_PRE Finish_PreFunction
!insertmacro MUI_PAGE_FINISH

; English Language files
!insertmacro MUI_LANGUAGE "English" ; first language is the default language
LangString License_Subtitle ${LANG_ENGLISH} "Please review the license terms before proceeding"
LangString License_Text_Top ${LANG_ENGLISH} "The software within this program falls under the following Licenses."
LangString License_Text_Bottom ${LANG_ENGLISH} "You must accept the terms of this License agreement to run this ${NAME}. If you agree, Click I Agree to Continue."
LangString SelectDist_Title ${LANG_ENGLISH} "Drive Selection and Distro Options Page"
LangString SelectDist_Subtitle ${LANG_ENGLISH} "Choose your Flash Drive, and a Distro, ISO/ZIP file.$\r$\nAdditional Distributions can be added each time this tool is run."
LangString DrivePage_Text ${LANG_ENGLISH} "Step 1: Select your USB Disk."
LangString Distro_Text ${LANG_ENGLISH} "Step 2: Select a Distribution from the list to put on your USB."
LangString IsoPage_Text ${LANG_ENGLISH} "Step 3: Select the $FileFormat (Name must be the same as above)."
LangString IsoPage_Title ${LANG_ENGLISH} "Select Your $FileFormat"
LangString Casper_Text ${LANG_ENGLISH} "Step 4: Set a Persistent file size for storing changes (Optional)."
LangString IsoFile ${LANG_ENGLISH} "$FileFormat file|$ISOFileName" ;$ISOFileName variable previously *.iso
LangString Extract ${LANG_ENGLISH} "Extracting the $FileFormat: The progress bar will not move until finished. Please be patient..."
LangString CreateSysConfig ${LANG_ENGLISH} "Creating configuration files for $DestDisk"
LangString ExecuteSyslinux ${LANG_ENGLISH} "Executing syslinux on $BootDir"
LangString SkipSyslinux ${LANG_ENGLISH} "Good Syslinux Exists..."
LangString WarningSyslinux ${LANG_ENGLISH} "An error ($R8) occurred while executing syslinux.$\r$\nYour USB drive won't be bootable..."
LangString WarningSyslinuxOLD ${LANG_ENGLISH} "This revision uses different Boot files that are not compatible with earlier revisions.$\r$\nPlease ensure your USB drive doesn't contain earlier revision installs."
LangString Install_Title ${LANG_ENGLISH} "$InUnStalling $InUnName"
LangString Install_SubTitle ${LANG_ENGLISH} "Please wait while we $InUnStall $InUnName $OnFrom $JustDrive"
LangString Install_Finish_Sucess ${LANG_ENGLISH} "${NAME} $InUnStalled $InUnName $OnFrom $JustDrive"
LangString Finish_Install ${LANG_ENGLISH} "Process Complete."
LangString Finish_Title ${LANG_ENGLISH} "Thanks for using ${NAME}"
LangString Finish_Text ${LANG_ENGLISH} "Your Selections have been $InUnStalled on your USB drive.$\r$\n$\r$\nFeel Free to run this tool again to $InUnStall more Distros.$\r$\n$\r$\nThe tool will keep track of selections you have already $InUnStalled."
LangString Finish_Link ${LANG_ENGLISH} "Visit the Project Home Page"

!include FileManipulation.nsh ; Text File Manipulation
!include FileNames.nsh ; Macro for FileNames
!include DistroList.nsh ; List of Distributions
!include StrContains.nsh ; Let's check if a * wildcard exists
!include "CasperScript.nsh" ; For creation of Persistent files

Function License_PreFunction
	StrCpy $R8 1 ;This is the 1st page
FunctionEnd

Function SelectionsPage
	StrCpy $R8 2
	!insertmacro MUI_HEADER_TEXT $(SelectDist_Title) $(SelectDist_Subtitle)
	nsDialogs::Create 1018
	Pop $Dialog
	Call HideVentoyUI
	
	${If} $RepeatInstall == "YES"
		;${NSD_SetText} $DestDriveTxt "$DestDrive"
		; To Install or Uninstall? That is the question!
		${NSD_CreateCheckBox} 60% 0 44% 15 "View or Remove Installed Distros?"
		Pop $Uninstaller
		${NSD_OnClick} $Uninstaller Uninstall
		
		; Distro Selection Starts (step 2)
		${NSD_CreateLabel} 0 50 50% 15 $(Distro_Text)
		Pop $LinuxDistroSelection
		${NSD_CreateDroplist} 0 70 55% 95 ""  ; create droplist
		Pop $Distro
		${NSD_OnChange} $Distro OnSelectDistro
		; remember this as the last valid selection
		StrCpy $LastValidDistroIndex 0
		${NSD_CB_SelectString} $Distro $DistroName
		
		; Force Show All ISO Option
		${NSD_CreateCheckBox} 80% 100 20% 15 "Show All ISOs?"
		Pop $ForceShowAll
		${NSD_OnClick} $ForceShowAll ShowAllISOs
		
		; ISO Download Option
		${NSD_CreateCheckBox} 60% 60 40% 15 "Download the ISO (Optional)."
		Pop $DownloadISO
		${NSD_OnClick} $DownloadISO DownloadIt
		
		; Clickable Link to Distribution Homepage
		${NSD_CreateLink} 60% 80 40% 15 "Visit the $OfficialName HomePage"
		Pop $DistroLink
		${NSD_OnClick} $DistroLink onClickLinuxSite
		
		; ISO Selection Starts (step 3)
		${NSD_CreateLabel} 0 100 100% 15 $(IsoPage_Text)
		Pop $LabelISOSelection
		${NSD_CreateText} 0 120 78% 20 "Disabled until step 2 is complete"
		Pop $ISOFileTxt
		${NSD_CreateBrowseButton} 85% 120 60 20 "Browse"
		Pop $ISOSelection
		${NSD_OnClick} $ISOSelection ISOBrowse
		
		; Debian based Persistence Selection Starts
		${NSD_CreateLabel} 0 150 75% 15 $(Casper_Text)
		Pop $CasperSelection1
		${NSD_CreateLabel} 52% 178 25% 25 ""
		Pop $SlideSpot1
		nsDialogs::CreateControl "msctls_trackbar32" "0x50010000|0x00000018" "" 0 174 50% 25 ""
		Pop $CasperSlider1
		; Range: 0 = none, 1 = 8GB, 2 = 16GB, 3 = 32GB
		SendMessage $CasperSlider1 ${TBM_SETRANGEMIN} 1 0
		SendMessage $CasperSlider1 ${TBM_SETRANGEMAX} 1 3
		SendMessage $CasperSlider1 ${TBM_SETTICFREQ} 1 1
		; Default = none selected
		SendMessage $CasperSlider1 ${TBM_SETPOS} 1 0
		${NSD_OnNotify} $CasperSlider1 onNotify_CasperSlider1
		
		; Casper-RW Selection Starts
		${NSD_CreateLabel} 0 150 75% 15 "Step 4: Slide to set a Size to use for Persistence (optional)"
		Pop $CasperSelection
		${NSD_CreateLabel} 52% 178 25% 25 ""
		Pop $SlideSpot
		nsDialogs::CreateControl "msctls_trackbar32" "0x50010000|0x00000018" "" 0 174 50% 25 ""
		Pop $CasperSlider
		SendMessage $CasperSlider ${TBM_SETRANGEMIN} 1 0 ; Min Range Value 0
		SendMessage $CasperSlider ${TBM_SETRANGEMAX} 1 $RemainingSpace ; Max Range Value $RemainingSpace
		${NSD_OnNotify} $CasperSlider onNotify_CasperSlider
		
		; Drive Pre-Selection
		${NSD_CreateLabel} 0 0 35% 15 ""
		Pop $LabelDrivePage
		
		; Droplist for Drive Selection
		${NSD_CreateDropList} 0 20 55% 15 ""
		Pop $DestDriveTxt
		Call ListAllDrives
		;${GetDrives} "FDD+HDD" DrivesList
		${If} $WINE == "WINE" ; Use WINE detected method
			${NSD_CB_SelectString} $DestDriveTxt "$DestDrive"
			StrCpy $9 $DestDrive 3
			StrCpy $JustDrive $9
			; Call PhysDrive
			Call GetDiskVolumeName
			Call DiskSpace
			; Call GetFSType
			StrCpy $JustDrive $DestDrive 3
			StrCpy $BootDir $DestDrive 2 ;was -1
			StrCpy $DestDisk $DestDrive 2 ;was -1
			SendMessage $Distro ${CB_RESETCONTENT} 0 0 ; Clear all distro entries because a new drive may have been chosen ; Enable for DropBox
			StrCpy $Checker "YES"
			Call InstallorRemove
			Call SetSpace
			Call CheckSpace
			Call FormatIt
			Call EnableNext
			${NSD_OnChange} $DestDriveTxt OnSelectDrive
		${EndIf}
		
		; Add Home Link
		${NSD_CreateLink} 0 215 16% 15 "Project Page"
		Pop $Link
		${NSD_OnClick} $Link onClickMyLink
		
		; Wipe Drive
		${NSD_CreateLink} 18% 215 15% 15 "WIPE Drive"
		Pop $Wipe
		${NSD_OnClick} $Wipe onClickMyLinkWIPE
		
		; Add Giveback Link
		${NSD_CreateLink} 35% 215 30% 15 "Recommended Flash Drives"
		Pop $Link2
		${NSD_OnClick} $Link2 onClickMyLinkUSB
		
		; Check for Latest Version
		${NSD_CreateLink} 70% 215 30% 15 "Check for Updates"
		Pop $VersionChk
		${NSD_OnClick} $VersionChk checker
		
		; Disable Next Button until a selection is made for all
		GetDlgItem $NXT $HWNDPARENT 1
		EnableWindow $NXT 0
		
		; Remove Back Button
		GetDlgItem $BCK $HWNDPARENT 3
		ShowWindow $BCK 0
		
		; Hide or disable steps until we state to display them
		EnableWindow $LabelISOSelection 0 ; disabled until step 2 is done
		EnableWindow $ISOFileTxt 0 ; disabled until step 2 is done
		;ShowWindow $LabelISOSelection 0 ; disabled until step 2 is done
		;ShowWindow $ISOFileTxt 0 ; disabled until step 2 is done		
		ShowWindow $ISOSelection 0
		EnableWindow $DownloadISO 0
		ShowWindow $ForceShowAll 0
		ShowWindow $DistroLink 0
		;ShowWindow $CasperSelection1 0
		;ShowWindow $CasperSlider1 0
		;ShowWindow $SlideSpot1 0
		StrCpy $JustISOName "NULL" ; Set to NULL until something is selected
		Call HideISOControls
		; Hide persistence if in uninstall or format/ventoy mode
		;Call RefreshUI
		nsDialogs::Show
	${Else}
		; To Install or Uninstall? That is the question!
		${NSD_CreateCheckBox} 60% 0 44% 15 "View or Remove Installed Distros?"
		Pop $Uninstaller
		${NSD_OnClick} $Uninstaller Uninstall
		
		; Drive Selection Starts
		${NSD_CreateLabel} 0 0 35% 15 ""
		Pop $LabelDrivePage
		${NSD_SetText} $LabelDrivePage "Step 1: Select your USB Device"
		
		; Droplist for Drive Selection
		${NSD_CreateDropList} 0 20 55% 15 ""
		Pop $DestDriveTxt
		Call ListAllDrives
		${NSD_OnChange} $DestDriveTxt OnSelectDrive
		
		; All Drives Option
		${NSD_CreateCheckBox} 36% 0 25% 15 "Redetect Disks?" ; was Show All?
		Pop $AllDriveOption
		${NSD_OnClick} $AllDriveOption ListAllDrives
		
		${If} $WINE != "WINE"
			; Format Drive Option
			${NSD_CreateCheckBox} 60% 23 100% 15 "Prepare Device"
			Pop $Format
			${NSD_OnClick} $Format FormatIt
		${EndIf}
		
		; Distro Selection Starts (step 2)
		${NSD_CreateLabel} 0 50 50% 15 $(Distro_Text)
		Pop $LinuxDistroSelection
		${NSD_CreateDroplist} 0 70 55% 95 ""  ; create droplist
		Pop $Distro
		${NSD_OnChange} $Distro OnSelectDistro
		; remember this as the last valid selection
		StrCpy $LastValidDistroIndex 0
		${NSD_CB_SelectString} $Distro $DistroName
		
		; Force Show All ISO Option
		${NSD_CreateCheckBox} 80% 100 20% 15 "Show All ISOs?"
		Pop $ForceShowAll
		${NSD_OnClick} $ForceShowAll ShowAllISOs
		
		; ISO Download Option
		${NSD_CreateCheckBox} 60% 60 40% 15 "Download the ISO (Optional)."
		Pop $DownloadISO
		${NSD_OnClick} $DownloadISO DownloadIt
		
		; Clickable Link to Distribution Homepage
		${NSD_CreateLink} 60% 80 40% 15 "Visit the $OfficialName HomePage"
		Pop $DistroLink
		${NSD_OnClick} $DistroLink onClickLinuxSite
		
		; ISO Selection Starts (step 3)
		${NSD_CreateLabel} 0 100 100% 15 $(IsoPage_Text)
		Pop $LabelISOSelection
		${NSD_CreateText} 0 120 78% 20 "$FileFormat selection disabled until step 1 & 2 are complete"
		Pop $ISOFileTxt
		${NSD_CreateBrowseButton} 85% 120 60 20 "Browse"
		Pop $ISOSelection
		${NSD_OnClick} $ISOSelection ISOBrowse
		
		; Debian based Persistence Selection Starts
		${NSD_CreateLabel} 0 150 75% 15 $(Casper_Text)
		Pop $CasperSelection1
		${NSD_CreateLabel} 52% 178 25% 25 ""
		Pop $SlideSpot1
		nsDialogs::CreateControl "msctls_trackbar32" "0x50010000|0x00000018" "" 0 174 50% 25 ""
		Pop $CasperSlider1
		; Range: 0 = none, 1 = 8GB, 2 = 16GB, 3 = 32GB
		SendMessage $CasperSlider1 ${TBM_SETRANGEMIN} 1 0
		SendMessage $CasperSlider1 ${TBM_SETRANGEMAX} 1 3
		SendMessage $CasperSlider1 ${TBM_SETTICFREQ} 1 1
		; Default = none selected
		SendMessage $CasperSlider1 ${TBM_SETPOS} 1 0
		${NSD_OnNotify} $CasperSlider1 onNotify_CasperSlider1
		
		; Casper-RW Selection Starts
		${NSD_CreateLabel} 0 150 75% 15 "Step 4: Slide to set a size to use for persistence (optional)"
		Pop $CasperSelection
		${NSD_CreateLabel} 52% 178 25% 25 ""
		Pop $SlideSpot
		nsDialogs::CreateControl "msctls_trackbar32" "0x50010000|0x00000018" "" 0 174 50% 25 ""
		Pop $CasperSlider
		SendMessage $CasperSlider ${TBM_SETRANGEMIN} 1 0 ; Min Range Value 0
		SendMessage $CasperSlider ${TBM_SETRANGEMAX} 1 $RemainingSpace ; Max Range Value $RemainingSpace
		${NSD_OnNotify} $CasperSlider onNotify_CasperSlider
		
		; Add Home Link
		${NSD_CreateLink} 0 215 16% 15 "Project Page"
		Pop $Link
		${NSD_OnClick} $link onClickMyLink
		
		${If} ${AtLeastWin10} ; checkpoint to test if is => Windows 10 to support features.
			; Wipe Drive
			${NSD_CreateLink} 18% 215 15% 15 "WIPE Drive"
			Pop $Wipe
			${NSD_OnClick} $Wipe onClickMyLinkWIPE
		${EndIf}
		
		; Add Giveback Link
		${NSD_CreateLink} 35% 215 30% 15 "Recommended Flash Drives"
		Pop $Link2
		${NSD_OnClick} $link2 onClickMyLinkUSB
		
		; Check for Latest Version
		${NSD_CreateLink} 70% 215 30% 15 "Check for Updates"
		Pop $VersionChk
		${NSD_OnClick} $VersionChk checker
		
		; Disable Next Button until a selection is made for all
		GetDlgItem $NXT $HWNDPARENT 1
		EnableWindow $NXT 0
		
		; Remove Back Button
		GetDlgItem $BCK $HWNDPARENT 3
		ShowWindow $BCK 0
		
		; Hide or disable steps until we state to display them
		EnableWindow $LabelISOSelection 0 ; disabled until step 2 is done
		EnableWindow $ISOFileTxt 0 ; disabled until step 2 is done	
		ShowWindow $ISOSelection 0
		EnableWindow $LinuxDistroSelection 0
		EnableWindow $Distro 0
		EnableWindow $DownloadISO 0
		ShowWindow $DistroLink 0
		ShowWindow $CasperSelection 0
		ShowWindow $CasperSlider 0
		ShowWindow $SlideSpot 0
		ShowWindow $Format 0
		ShowWindow $ForceShowAll 0
		ShowWindow $Uninstaller 0
		ShowWindow $CasperSelection1 0
		ShowWindow $CasperSlider1 0
		ShowWindow $SlideSpot1 0
		; ShowWindow $Wipe 0
		Call HideISOControls
		;Call RefreshUI
		nsDialogs::Show
	${EndIf}
FunctionEnd

Function InstFiles_PreFunction
	StrCpy $R8 3
FunctionEnd

Function Finish_PreFunction
	StrCpy $R8 4
	Call NoQuit
FunctionEnd

Function ListAllDrives ; Set to Display All Drives
	; SendMessage $DestDriveTxt ${CB_RESETCONTENT} 0 0
	${NSD_GetState} $AllDriveOption $DisplayAll
	${If} $DisplayAll == ${BST_CHECKED}
		${NSD_Check} $AllDriveOption
		${NSD_SetText} $AllDriveOption "Refreshed Disks" ; was All Shown!
		${If} $WINE == "WINE" ; Use WINE detected method
			SendMessage $DestDriveTxt ${CB_RESETCONTENT} 0 0
			${GetDrives} "FDD+HDD" DrivesList ; All Drives Listed
		${Else}
			Call DrivesList  ;${GetDrives} "FDD+HDD" DrivesList ; All Drives Listed
			Call SelectDrive
		${EndIf}
	${ElseIf} $DisplayAll == ${BST_UNCHECKED}
		${NSD_Uncheck} $AllDriveOption
		${NSD_SetText} $AllDriveOption "Redetect Disks?" ; was $Show ALL?
		${If} $WINE == "WINE" ; Use WINE detected method
			SendMessage $DestDriveTxt ${CB_RESETCONTENT} 0 0
			${GetDrives} "FDD+HDD" DrivesList ; All Drives Listed
		${Else}
			Call DrivesList ;${GetDrives} "FDD" DrivesList ; FDD+HDD reduced to FDD for removable media only
			Call SelectDrive
		${EndIf}
	${EndIf}
FunctionEnd

Function onClickMyLink
	Pop $Links ; pop something to prevent corruption
	ExecShell "open" "https://pendrivelinux.com/universal-usb-installer-easy-as-1-2-3/"
FunctionEnd

Function onClickMyLinkWIPE
	Pop $Wipe ; pop something to prevent corruption
	; ExecShell "open" "https://pendrivelinux.com/restoring-your-usb-key-partition/"
    Call WipeDrive
FunctionEnd

Function onClickMyLinkUSB
	Pop $Links2 ; pop something to prevent corruption
	ExecShell "open" "https://pendrivelinux.com/fastest-usb-flash-drives/"
FunctionEnd

Function onClickLinuxSite
	Pop $OfficialSite
	ExecShell "open" "$Homepage"
FunctionEnd

Function DownloadIt ; Set Download Option
	${NSD_GetState} $DownloadISO $DownloadMe
	${If} $DownloadMe == ${BST_CHECKED}
		${NSD_Check} $DownloadISO
		${NSD_SetText} $DownloadISO "Opened Download Link"
		Call DownloadLinks
	${ElseIf} $DownloadMe == ${BST_UNCHECKED}
		${NSD_Uncheck} $DownloadISO
		${NSD_SetText} $DownloadISO "Download Link"
	${EndIf}
FunctionEnd

Function EnableNext ; Enable Install Button
	; ${If} $Blocksize >= 4
	${If} $Removal != "YES"
		${If} $WINE != "WINE" ; IfNot WINE method
			ShowWindow $Format 1
		${EndIf} ; EndIfNot WINE
		; ShowWindow $Wipe 1
	${Else}
		ShowWindow $Format 0
		; ShowWindow $Wipe 0
	${EndIf}
	
	${If} $Removal != "YES"
	${AndIf} ${FileExists} "$BootDir\UUI\*.*"
	${OrIf} $VolName == "Ventoy" ; Ventoy was installed
	${AndIf} $ISOFileName != ""
	${AndIf} $ISOFile != ""
	${AndIf} $DestDrive != ""
	${AndIf} $ISOTest != ""
		StrCpy $InUnStall "Add"
		StrCpy $InUnStalling "Adding"
		StrCpy $InUnStalled "Added"
		StrCpy $OnFrom "to"
		StrCpy $InUnName "$JustISOName"
		GetDlgItem $NXT $HWNDPARENT 1 ; Get "Install" control handle
		SendMessage $NXT ${WM_SETTEXT} 0 "STR:Create"
		EnableWindow $NXT 1 ; Enable "Install" control button
	${ElseIf} $Removal == "YES"
	${AndIf} $ISOFileName != ""
	${AndIf} $DestDrive != ""
	${AndIf} $ISOTest != ""
		StrCpy $InUnStall "Remove"
		StrCpy $InUnStalling "Removing"
		StrCpy $InUnStalled "Removed"
		StrCpy $OnFrom "from"
		StrCpy $InUnName "$DistroName"
		GetDlgItem $NXT $HWNDPARENT 1 ; Get "Install" control handle
		SendMessage $NXT ${WM_SETTEXT} 0 "STR:Remove"
		EnableWindow $NXT 1 ; Enable "Install" control button
	${EndIf}
	
	; Test if ISO has been Selected. If not, disable Install Button
	${If} $ISOTest == ""
		GetDlgItem $NXT $HWNDPARENT 1
		EnableWindow $NXT 0 ; Disable "Install" if ISO not set
	${EndIf}
	
	; Show Steps in progression
	${If} $DestDrive != ""
	${AndIf} ${FileExists} "$BootDir\UUI\*.*"
	${OrIf} $VolName == "Ventoy" ; Ventoy was installed
		;MessageBox MB_OK "UUI exists"
		EnableWindow $LinuxDistroSelection 1
		EnableWindow $Distro 1
	${Else}
		;MessageBox MB_OK "UUI Does Not exist"
		EnableWindow $LinuxDistroSelection 0
		EnableWindow $Distro 0
	${EndIf}
	
    ${If} $ISOFileName != ""
    ${AndIf} $Removal != "YES"
	    EnableWindow $LabelISOSelection 1
	    EnableWindow $ISOFileTxt 1
	    ShowWindow $ISOSelection 1
    ${ElseIf} $Removal == "YES"
	    EnableWindow $LabelISOSelection 0
	    EnableWindow $ISOFileTxt 0
	    ShowWindow $LabelISOSelection 0
	    ShowWindow $ISOFileTxt 0
	    ShowWindow $ISOSelection 0
    ${EndIf}

	; Disable Window if ISO was downloaded
	${If} $TheISO == "$EXEDIR\$ISOFileName"
	${AndIf} $ISOTest != ""
		EnableWindow $ISOSelection 0
		SetCtlColors $ISOFileTxt 009900 FFFFFF
	${EndIf}
	
; Always reset first
ShowWindow $CasperSelection 0
ShowWindow $CasperSlider 0
ShowWindow $SlideSpot 0
ShowWindow $CasperSelection1 0
ShowWindow $CasperSlider1 0
ShowWindow $SlideSpot1 0

; If using Casper or vtcow not live Persistence...
${If} $Persistence != "live"
${AndIf} $Persistence != "NULL"
${AndIf} $Removal != "YES"
${AndIf} $ISOTest != ""
${AndIf} $TheISO != ""
${AndIf} $BootDir != ""
    ShowWindow $CasperSelection 1
    ShowWindow $CasperSlider 1
    ShowWindow $SlideSpot 1

; If using Debian live Persistence...
${ElseIf} $Persistence == "live"
${AndIf} $Removal != "YES"
${AndIf} $ISOTest != ""
${AndIf} $TheISO != ""
${AndIf} $BootDir != ""
    ShowWindow $CasperSelection1 1
    ShowWindow $CasperSlider1 1
    ShowWindow $SlideSpot1 1
${EndIf}
	
FunctionEnd

Function DownloadLinks
	MessageBox MB_YESNO|MB_ICONQUESTION "Launch the Download Link?$\r$\nLet the download finish before moving to step 2." IDYES DownloadIt IDNO Skip
	Skip: ; Reset Download Checkbox Options
		${NSD_Uncheck} $DownloadISO
		${NSD_SetText} $DownloadISO "Download Link"
		EnableWindow $DownloadISO 1
		Goto end
	DownloadIt:
		${NSD_SetText} $LabelISOSelection "Step 3: Once your download has finished, Browse and select the ISO."
		EnableWindow $DownloadISO 0
		ExecShell "open" "$DownLink"
	end:
FunctionEnd

Function LocalISODetected ; The script autodetected the ISO, so let's do the following
	${If} $DownloadMe != ${BST_CHECKED}
	${AndIf} $LocalSelection != "YES"
		StrCpy $ISOFile "$EXEDIR\$ISOFileName"
	${EndIf}
FunctionEnd

; get only the filename
Function GrabNameOnly
	Exch $4 ; count to get part
	Exch
	Exch $0 ; input string
	Push $1
	Push $2
	Push $3
	StrCpy $1 0
	StrCpy $3 1
	loop:
		IntOp $1 $1 - 1
		StrCpy $2 $0 1 $1
		StrCmp $2 "" exit2
		StrCmp $2 "\" next ; grab text to the right of "\"
		Goto loop
	next:
		StrCmp $3 $4 exit
		IntOp $3 $3 + 1
		Goto loop
	exit2:
		IntOp $1 $1 - 1
	exit:
		IntOp $1 $1 + 1
		StrCpy $0 $0 "" $1
		Pop $3
		Pop $2
		Pop $1
		Exch $0 ; output string
FunctionEnd

; On Selection of Linux Distro
Function OnSelectDistro
	Call ClearAll
	Pop $Distro
	SendMessage $Distro ${CB_GETCURSEL} 0 0 $0
	${NSD_GetText} $Distro $1
	; Empty entry?
	StrCmp $1 "" is_invalid
	; Header?
	StrCpy $2 $1 3
	StrCmp $2 "---" is_invalid
	StrCpy $LastValidDistroIndex $0
	Goto continue
	is_invalid:
		SendMessage $Distro ${CB_SETCURSEL} $LastValidDistroIndex 0
		Return
	continue:
		${If} $Removal == "YES"
			ShowWindow $ForceShowAll 0
		${Else}
			ShowWindow $ForceShowAll 1
		${EndIf}
		
		${NSD_GetText} $Distro $DistroName
		StrCpy $DistroName "$DistroName"
		StrCpy $Checker "No"
		
		${If} $Removal == "YES"
			StrCpy $ISOFileName "$DistroName"
			StrCpy $ISOTest "$DistroName"
		${Else}
			Call SetISOFileName
			StrCpy $ISOFileName "$ISOFileName"
			StrCpy $SomeFileExt "$ISOFileName" "" -3 ; Grabs the last 3 characters of the file name... zip or iso?
			StrCpy $FileFormat "$SomeFileExt" ; Set file type to look for zip, tar, iso etc...
			${NSD_SetText} $LabelISOSelection "Step 3: Browse and Select your $ISOFileName"
			${NSD_SetText} $ISOFileTxt "Browse to your $ISOFileName  -->"
			SetCtlColors $ISOFileTxt FF0000 FFFFFF
			StrCpy $ISOTest "" ; Set to null until a new ISO selection is made
		${EndIf}
		
		${If} $DistroName == "Phoenix LiteOS"
		${OrIf} $DistroName == "Windows X-Lite"
			${NSD_SetText} $CasperSelection "Step 4: Optional - use sider to override default 30GB VHDx filesize. ($RemainingSpace MB) left."
		${Else}
			${NSD_SetText} $CasperSelection "$(Casper_Text)"
		${EndIf}
		
		; Redraw Home page Links
		${NSD_SetText} $DistroLink "Visit the $OfficialName Home Page"
		ShowWindow $DistroLink 0
		${If} $OfficialName == ""
		${OrIf} $Removal == "YES"
			ShowWindow $DistroLink 0
		${Else}
			ShowWindow $DistroLink 1
		${EndIf}
		
		; Autodetect ISO's in same folder and select if they exist
		${If} ${FileExists} "$EXEDIR\$ISOFileName"
		${AndIf} $Removal != "YES"
			${StrContains} $WILD "*" "$ISOFileName" ; Check for Wildcard and force Browse if * exists.
		${AndIf} $WILD != "*"
			StrCpy $TheISO "$EXEDIR\$ISOFileName"
			StrCpy $ISOFile "$TheISO"
			${GetFileName} "$TheISO" $JustISO
			${GetBaseName} "$JustISO" $JustISOName
			${StrRep} '$JustISOName' '$JustISOName' ' ' '-'
			${StrRep} $JustISOName "$JustISOName" "'" ""
			${GetParent} "$TheISO" $JustISOPath
			EnableWindow $DownloadISO 0
			${NSD_SetText} $DownloadISO "We Found and Selected the $SomeFileExt."
			EnableWindow $ISOSelection 0
			SetCtlColors $ISOFileTxt 009900 FFFFFF
			${NSD_SetText} $ISOFileTxt $ISOFile
			${NSD_SetText} $LabelISOSelection "Step 3 DONE: $ISOFileName Found and Selected!"
			StrCpy $ISOTest "$TheISO" ; Populate ISOTest so we can enable Next
			Call EnableNext
		${ElseIf} ${FileExists} "$EXEDIR\$ISOFileName"
		${AndIf} $Removal != "YES"
		${AndIf} $WILD == "*"
			EnableWindow $DownloadISO 1
			EnableWindow $ISOSelection 1
			${NSD_Uncheck} $DownloadISO
			${NSD_SetText} $DownloadISO "Download Link"
			SetCtlColors $ISOFileTxt FF9B00 FFFFFF
			${NSD_SetText} $ISOFileTxt "Browse to and select the $ISOFileName"
			${NSD_SetText} $LabelISOSelection "Step 3 PENDING: Browse to your $ISOFileName"
			Call EnableNext
		${Else}
			Call EnableNext
			EnableWindow $DownloadISO 1
			EnableWindow $ISOSelection 1
			${NSD_Uncheck} $DownloadISO
			${NSD_SetText} $DownloadISO "Download Link"
		${EndIf}
		
		${If} $DownLink == "NONE"
		${OrIf} $Removal == "YES"
			ShowWindow $DownloadISO 0
		${Else}
			ShowWindow $DownloadISO 1
		${EndIf}
		
		${If} $DistroName == "Try an Unlisted ISO/IMG"
			ShowWindow $ForceShowAll 0
		${EndIf}
FunctionEnd

; On Selection of ISO File
Function ISOBrowse
	${If} $ShowingAll == "YES"
		StrCpy $ISOFileName "*.iso"
	${ElseIf} $ShowingAll != "YES"
		Call SetISOFileName
	${EndIf}
	
	nsDialogs::SelectFileDialog open "" $(IsoFile)
	Pop $TheISO
	${NSD_SetText} $ISOFileTxt $TheISO
	SetCtlColors $ISOFileTxt 009900 FFFFFF
	EnableWindow $DownloadISO 0
	${NSD_SetText} $DownloadISO "Local $SomeFileExt Selected."
	StrCpy $ISOTest "$TheISO" ; Populate ISOTest so we can enable Next
	StrCpy $ISOFile "$TheISO"
	${GetFileName} "$TheISO" $JustISO
	${StrRep} '$JustISO' '$JustISO' ' ' '-'
	${GetBaseName} "$JustISO" $JustISOName
	${StrRep} '$JustISOName' '$JustISOName' ' ' '-'
	${StrRep} $JustISOName "$JustISOName" "'" ""
	${GetParent} "$TheISO" $JustISOPath
	StrCpy $LocalSelection "YES"
	Call SetISOSize
	Call SetSpace
	Call CheckSpace
	Call HaveSpacePre
	
	${If} $JustISOName == ""
		StrCpy $JustISOName "NULL" ; Set to NULL until something is selected
	${EndIf}
	
	${If} ${FileExists} "$BootDir\UUI\$DistroPath\$JustISO"
	${AndIf} $JustISOName != ""
	${AndIf} $FormatChoice != "YES"
		MessageBox MB_OK "$BootDir\UUI\$DistroPath\$JustISO is already installed. You should remove it first!$\r$\n$\r$\nIf you proceed without manual removal, this tool will automatically remove and replace the directory and files for you."
	${EndIf}
	
	Call EnableNext
FunctionEnd

Function ClearAll
	StrCpy $ISOTest ""
	StrCpy $DistroName "" ; Clear Distro Name
	StrCpy $ISOFileName "" ; Clear ISO Selection
	StrCpy $SomeFileExt ""
	StrCpy $FileFormat ""
	StrCpy $JustISO ""
	StrCpy $JustISOName ""
	StrCpy $Persistence "" ; Just clear the Null
	; StrCpy $ISOFile ""
	; StrCpy $Casper ""
	;SendMessage $CasperSelection ${BM_SETCHECK} ${BST_UNCHECKED} 0
	ShowWindow $CasperSelection 0
	ShowWindow $CasperSlider 0
	ShowWindow $SlideSpot 0
	;SendMessage $CasperSelection1 ${BM_SETCHECK} ${BST_UNCHECKED} 0
	ShowWindow $CasperSelection1 0
	ShowWindow $CasperSlider1 0
	ShowWindow $SlideSpot1 0
FunctionEnd

Function InstallorRemove ; Populate DistroName based on Install/Removal option
	${If} $Removal == "YES"
		Call RemovalList
		Call ClearAll
	${Else}
		${NSD_SetText} $LinuxDistroSelection "Step 2: Select a Distribution to put on $DestDisk"
		${If} $VENTOY_ACTIVE != 1
			ShowWindow $AllDriveOption 1
		${EndIf}
		Call SetISOFileName
	${EndIf}
FunctionEnd

; On Selection of Uninstaller Option
Function Uninstall
	${NSD_GetState} $Uninstaller $Removal
	${If} $Removal == ${BST_CHECKED}
		ShowWindow $Format 0
		; ShowWindow $Wipe 0
		
		EnableWindow $LabelISOSelection 0 ; disabled in uninstaller
		EnableWindow $ISOFileTxt 0 ; disabled in uninstaller
		ShowWindow $LabelISOSelection 0 ; disabled in uninstaller 
		ShowWindow $ISOFileTxt 0 ; disabled in uninstaller		
		
		Call ClearAll
		
		ShowWindow $AllDriveOption 0
		ShowWindow $ISOFileTxt 0
		ShowWindow $ISOSelection 0
		ShowWindow $ForceShowAll 0
		ShowWindow $CasperSelection 0
		ShowWindow $CasperSlider 0
		ShowWindow $SlideSpot 0
		StrCpy $Persistence "NULL"
		ShowWindow $CasperSelection1 0
		ShowWindow $CasperSlider1 0
		ShowWindow $SlideSpot1 0
		${NSD_Check} $Uninstaller
		StrCpy $Removal "YES"
		ShowWindow $DistroLink 0
		ShowWindow $DownloadISO 0
		GetDlgItem $NXT $HWNDPARENT 1 ; Get "Install" control handle
		SendMessage $NXT ${WM_SETTEXT} 0 "STR:Remove"
		EnableWindow $NXT 0 ; Disable "Install" control button
		${NSD_SetText} $Uninstaller "You're in Uninstaller Mode!"
		${NSD_SetText} $LinuxDistroSelection "Step 2: Select a Distribution to remove."
		SendMessage $Distro ${CB_RESETCONTENT} 0 0 ; Clear all distro entries because a new option may have been chosen ; Enable for DropBox
		StrCpy $Checker "YES"
		${If} $WINE != "WINE" ; WINE not detected method
			Call DrivesList
			Call SelectDrive
		${Else}
			Call RemovalList
		${EndIf} ; EndIfNot WINE
	${ElseIf} $Removal == ${BST_UNCHECKED}
		${If} $WINE != "WINE" ; WINE not detected method
			ShowWindow $Format 1
		${EndIf} ; EndIfNot WINE
		; ShowWindow $Wipe 1
		ShowWindow $LabelISOSelection 1
		ShowWindow $ISOFileTxt 1
		ShowWindow $ISOSelection 0
		Call ClearAll
		ShowWindow $CasperSelection 0
		ShowWindow $CasperSlider 0
		ShowWindow $SlideSpot 0
		StrCpy $Persistence "NULL"
		ShowWindow $CasperSelection1 0
		ShowWindow $CasperSlider1 0
		ShowWindow $SlideSpot1 0
		${NSD_SetText} $LabelISOSelection "Step 3: Select your $ISOFileName"
		${NSD_SetText} $ISOFileTxt "$FileFormat selection disabled until step 1 & 2 are complete"
		GetDlgItem $NXT $HWNDPARENT 1 ; Get "Install" control handle
		SendMessage $NXT ${WM_SETTEXT} 0 "STR:Create"
		EnableWindow $NXT 0 ; Disable "Install" control button
		${NSD_Uncheck} $Uninstaller
		StrCpy $Removal ""
		${NSD_SetText} $Uninstaller "View or Remove Installed Distros?"
		${NSD_SetText} $LinuxDistroSelection "Step 2: Select a Distribution to put on $DestDisk"
		SendMessage $Distro ${CB_RESETCONTENT} 0 0  ; Clear all distro entries because a new option may have been chosen ; Enable for DropBox
		StrCpy $Checker "YES"
		${If} $WINE != "WINE" ; WINE not detected method
			Call DrivesList
			Call SelectDrive
		${Else}
			;Call OnSelectDrive
		${EndIf} ; EndIfNot WINE
		Call SetISOFileName
	${EndIf}
FunctionEnd

Function NoSpace
	ShowWindow $Format 0
	Call ClearAll
	EnableWindow $LabelISOSelection 0
	EnableWindow $ISOFileTxt 0
	ShowWindow $AllDriveOption 0
	ShowWindow $ISOSelection 0
	ShowWindow $ForceShowAll 0
	ShowWindow $CasperSelection 0
	ShowWindow $CasperSlider 0
	ShowWindow $SlideSpot 0
	StrCpy $Persistence "NULL"
	ShowWindow $DistroLink 0
	ShowWindow $DownloadISO 0
	${If} $WINE != "WINE" ; WINE not detected method
		ShowWindow $Format 1
	${EndIf} ; EndIfNot WINE
	ShowWindow $LabelISOSelection 1
	ShowWindow $ISOFileTxt 1
	${NSD_SetText} $LabelISOSelection "Step 3: Select your $ISOFileName (Not Enough Space)"
	${NSD_SetText} $ISOFileTxt "$FileFormat selection disabled until step 1 & 2 are complete"
	GetDlgItem $NXT $HWNDPARENT 1 ; Get "Install" control handle
	SendMessage $NXT ${WM_SETTEXT} 0 "STR:Create"
	EnableWindow $NXT 0 ; Disable "Install" control button
	${NSD_SetText} $Uninstaller "View or Remove Installed Distros?"
	${NSD_SetText} $LinuxDistroSelection "Step 2: Select a Distribution to put on $DestDisk"
	SendMessage $Distro ${CB_RESETCONTENT} 0 0  ; Clear all distro entries because a new option may have been chosen ; Enable for DropBox
	StrCpy $Checker "YES"
	${If} $WINE != "WINE" ; WINE not detected method
		Call DrivesList
		Call SelectDrive
	${Else}
	${EndIf} ; EndIfNot WINE
	Call SetISOFileName
FunctionEnd

Function SelectDrive
	${If} $JustDrive != ""
		;MessageBox MB_OK "$JustDrive"
		${NSD_CB_SelectString} $DestDriveTxt "$JustDrive" ; was $DestDrive
		${NSD_GetText} $DestDriveTxt $Letters
		StrCpy $DestDrive "$Letters"
		StrCpy $JustDrive $DestDrive 3
		StrCpy $BootDir $DestDrive 2 ;was -1
		StrCpy $DestDisk $DestDrive 2 ;was -1
		Call PhysDrive
		StrCpy $INST_DISK "$DiskNum" ; save Install Disk Number in case we need it again later
		Call GetDiskVolumeName
		Call DiskSpace
		Call GetFSType
		SendMessage $Distro ${CB_RESETCONTENT} 0 0 ; Clear all distro entries because a new drive may have been chosen
		${If} $WINE == "WINE" ; WINE detection method
			${NSD_SetText} $LabelDrivePage "Step 1: You chose $DestDrive"
		${Else}
			${NSD_SetText} $LabelDrivePage "Step 1: You chose (Disk $DiskNum)" ; was $DestDrive
		${EndIf} ; EndIf WINE detection method
		StrCpy $Checker "YES"
		Call InstallorRemove
		Call SetSpace
		Call CheckSpace
		Call FormatIt
		Call EnableNext
	${EndIf}
	${NSD_OnChange} $DestDriveTxt OnSelectDrive
FunctionEnd

Function postSelectDrive
	${If} $JustDrive != ""
		;MessageBox MB_OK "$JustDrive"
		${NSD_CB_SelectString} $DestDriveTxt "$JustDrive" ; was $DestDrive
		${NSD_GetText} $DestDriveTxt $Letters
		StrCpy $DestDrive "$Letters"
		StrCpy $JustDrive $DestDrive 3
		StrCpy $BootDir $DestDrive 2 ;was -1
		StrCpy $DestDisk $DestDrive 2 ;was -1
		Call PhysDrive
		StrCpy $INST_DISK "$DiskNum" ; save Install Disk Number in case we need it again later
		Call GetDiskVolumeName
		Call DiskSpace
		Call GetFSType
		SendMessage $Distro ${CB_RESETCONTENT} 0 0 ; Clear all distro entries because a new drive may have been chosen
		${NSD_SetText} $LabelDrivePage "Step 1: You chose (Disk $DiskNum)" ; was $DestDrive
		StrCpy $Checker "YES"
		Call InstallorRemove
		Call SetSpace
		Call CheckSpace
		;Call FormatIt
		Call EnableNext
	${EndIf}
	${NSD_OnChange} $DestDriveTxt OnSelectDrive
FunctionEnd

; On Selection of USB Drive
Function OnSelectDrive
	${If} $WINE == "WINE" ; WINE method
		Pop $DestDriveTxt
	${EndIf}
	
	${NSD_GetText} $DestDriveTxt $Letters
	StrCpy $DestDrive "$Letters"
	StrCpy $JustDrive $DestDrive 3
	StrCpy $BootDir $DestDrive 2 ;was -1
	StrCpy $DestDisk $DestDrive 2 ;was -1
	
	${If} $WINE != "WINE" ; WINE Not detected method
		Call PhysDrive
		StrCpy $INST_DISK "$DiskNum" ; save Install Disk Number in case we need it again later
		Call GetFSType
	${EndIf}
	
	Call ToInstallOrNot
	SendMessage $Distro ${CB_RESETCONTENT} 0 0 ; Clear all distro entries because a new drive may have been chosen ; Enable for DropBox
	StrCpy $Checker "YES"
	Call InstallorRemove
	Call SetSpace
	Call CheckSpace
	Call FormatIt
	Call EnableNext
	
	${If} $WINE == "WINE" ; WINE detection method
		${NSD_SetText} $LabelDrivePage "Step 1: You chose $DestDrive"
	${Else}
		${NSD_SetText} $LabelDrivePage "Step 1: You chose (Disk $DiskNum)" ; was $DestDrive
	${EndIf} ; EndIf WINE detection method
FunctionEnd

Function ToInstallOrNot
	${If} $WINE != "WINE" ; WINE not detected method
		; Check if drive is already prepared
		${StrContains} $VolName "Ventoy" "$Letters" ; set the volume label to check for before running the following $VolName conditional test.
		${If} $DestDrive != ""
		${AndIfNot} ${FileExists} "$BootDir\UUI\*.*"
		${AndIfNot} $VolName == "Ventoy"
		${AndIfNot} $RepeatInstall == "YES"
			StrCpy $FormatChoice ""
			${NSD_SetText} $Format "Prepare this Device?"
			;SetCtlColors $Format 0xFF0000 0x00FF00
	        StrCpy $ReUpdate "NO"
	        StrCpy $DrivePrepared "NO"			
			EnableWindow $Format 1
			ShowWindow $Format 1
			ShowWindow $Uninstaller 0 ; Don't display the Uninstaller on disks that don't have anything on them.
		${Else} ;${ElseIf} ${FileExists} "$BootDir\UUI\*.*"
			${NSD_SetText} $Format "Reinstall or Update?"
			 StrCpy $ReUpdate "YES"
	         StrCpy $DrivePrepared "YES"
			ShowWindow $Uninstaller 1 ; Re-enable Uninstaller option.
		${EndIf}
	${Else}
		ShowWindow $Uninstaller 1 ; enable Uninstaller option.
	${EndIf} ; EndIf WINE not detected
FunctionEnd

Function Checker
	; Download latest version number
	inetc::get /caption "Checking for latest version" /banner "Getting info" /nocancel "https://pendrivelinux.com/downloads/uuiversion.txt" "$PLUGINSDIR\uuiversion.txt" /end
	
	; Read single line
	FileOpen $0 "$PLUGINSDIR\uuiversion.txt" r
	FileRead $0 $Online_Version
	FileClose $0
	
	; Remove all CR/LF from $Online_Version
	StrCpy $2 ""
	StrCpy $3 0
	loop_trim:
		StrCpy $4 $Online_Version 1 $3
		StrCmp $4 "" done_trim
		StrCmp $4 0D skip 0
		StrCmp $4 0A skip 0
		StrCpy $2 $2$4
	skip:
		IntOp $3 $3 + 1
		Goto loop_trim
	done_trim:
		StrCpy $Online_Version $2
	
	; Compare versions
	${If} "$Online_Version" == ""
		MessageBox MB_ICONEXCLAMATION "Could not detect latest version."
		Return
	${EndIf}
	
	${If} "${VERSION}" == "$Online_Version"
		${If} "$RecentVersionDisplay" == "YES"
			MessageBox MB_ICONEXCLAMATION "You're currently using the most recent version of UUI ($Online_Version)."
		${EndIf}
	${Else}
		MessageBox MB_YESNO|MB_ICONQUESTION "You're using UUI ${VERSION}$\r$\n$\r$\nUUI $Online_Version version is available for download.$\r$\n$\r$\nWould you like to go to the latest version?" IDYES Takeme IDNO Dontgo
		Takeme:
			; Open the fixed URL in browser
			ExecShell "open" "https://pendrivelinux.com/universal-usb-installer-easy-as-1-2-3/#download-universal-usb-installer"
		Dontgo:
	${EndIf}
FunctionEnd

Function ExecFAT
	StrCpy $Ventoy_Version "${Ventoy_Version}"
	${If} ${FileExists} "$EXEDIR\Ventoy2Disk.exe"
		MessageBox MB_ICONEXCLAMATION "You will now be taken to Ventoy2Disk to create a Ventoy based UUI bootable USB.$\r$\n$\r$\n1.) NOTE: You will need to reselect your USB device.$\r$\n$\r$\n2.) Then, click Install to put Ventoy on your USB device.$\r$\n$\r$\n3.) Once finished, close Ventoy2Disk and return to UUI to continue."
		; Now launching Ventoy2Disk...
		${NSD_Uncheck} $Format ; disable format option so that it doesn't repeat on return.
		nsExec::Exec 'cmd /k cd /D "$EXEDIR"&Ventoy2Disk.exe $JustDrive'
		Call ListAllDrives
	${Else}
		${If} ${FileExists} "$PLUGINSDIR\ventoy-windows.zip"
			SetOutPath $PLUGINSDIR
			ExecWait '"$PLUGINSDIR\7zG.exe" x "$PLUGINSDIR\ventoy-windows.zip" -o"$PLUGINSDIR" -y'
			ExpandEnvStrings $COMSPEC "%COMSPEC%"
			; Prevent Drive with a Windows System directory from being selected
			${If} "$BootDir\" != "$SysDrive" ; System Drive detection method replaces Disk 0 method
			${AndIfNot} ${FileExists} "$BootDir\windows\system32" ; additional safeguard to help protect from mishap.
			${AndIfNot} ${FileExists} "$BootDir\excludedrive.txt" ; text file that can be added to a drive to prevent it from appearing.
			${AndIf} $DestDrive != ""
			${AndIfNot} ${FileExists} "$BootDir\UUI\*.*"
				MessageBox MB_YESNO|MB_ICONEXCLAMATION "You selected $Letters$\r$\n$\r$\n=============== WARNING! ===============$\r$\n$\r$\nBackup any data you want to keep before proceeding! All Data on (Disk $DiskNum) including any attached drive letters, partitions and volumes, even if hidden, will be wiped.$\r$\n$\r$\n${NAME} is ready to perform the following actions:$\r$\n$\r$\n1.) Wipe (Disk $DiskNum) - Data will be Irrecoverably Deleted!$\r$\n$\r$\n2.) Recreate drive letter ($DestDisk) with an $VTOY_FS_VAL formatted partition.$\r$\n$\r$\n3.) Create a secondary VTOYEFI partition on (Disk $DiskNum) - existing MBR will be Overwritten!$\r$\n$\r$\n4.) Create a UUI Label on ($DestDisk)$\r$\n$\r$\nBefore proceeding be sure (Disk $DiskNum) is the correct Disk.$\r$\nYou can double check with Windows diskmgmt to make sure!$\r$\n$\r$\nClick YES to perform these actions or NO to Abort." IDYES proceed
				${If} $WINE != "WINE"
					EnableWindow $Format 1
					ShowWindow $Format 1
				${EndIf}
				StrCpy $FormatChoice ""
				${NSD_SetState} $FormatMe ${BST_UNCHECKED}
				${NSD_Uncheck} $Format
				${NSD_SetText} $Format "Prepare this Device?"
				Goto skipprep
			proceed:
                ExecShell "" '"$COMSPEC"' '/C if 1==1 "$PLUGINSDIR\ventoy-$Ventoy_Version\Ventoy2Disk.exe" VTOYCLI /I /Drive:$BootDir /NOUSBCheck $VTOY_ARGS' SW_HIDE																																						 
				;ExecShell "" '"$COMSPEC"' '/C if 1==1 "$PLUGINSDIR\ventoy-$Ventoy_Version\Ventoy2Disk.exe" VTOYCLI /I /Drive:$BootDir /NOUSBCheck' SW_HIDE
				Banner::show /set 76 "Now Preparing and Installing Bootloader files."
				EnableWindow $Format 0
				ShowWindow $Format 0
			${Else}
			
				MessageBox MB_YESNO|MB_ICONEXCLAMATION "You selected $Letters$\r$\n$\r$\n=========== UPDATING Bootloader ===========$\r$\n$\r$\n${NAME} is ready to perform the following actions:$\r$\n$\r$\n1.) Update ${NAME} theme and configuration files along with the Ventoy $Ventoy_Version bootloader files on (Disk $DiskNum).$\r$\n$\r$\nClick YES to perform this Update or NO to Abort." IDYES update-it
				${If} $WINE != "WINE"
					EnableWindow $Format 1
					ShowWindow $Format 1
				${EndIf}
				StrCpy $FormatChoice ""
				${NSD_SetState} $FormatMe ${BST_UNCHECKED}
				${NSD_Uncheck} $Format
				;${NSD_SetText} $Format "Update/Reinstall?"
				Goto skipprep
			update-it:
				ExecShell "" '"$COMSPEC"' '/C if 1==1 "$PLUGINSDIR\ventoy-$Ventoy_Version\Ventoy2Disk.exe" VTOYCLI /U /Drive:$BootDir /NOUSBCheck' SW_HIDE
				Banner::show /set 76 "Now Updating Bootloader files."
			${EndIf}
			
			Banner::getWindow
			Pop $1
			Call cli_percent
			
			${If} ${FileExists} "$PLUGINSDIR\ventoy-$Ventoy_Version\cli_done.txt"
				; Ventoy's fresh install wipes the disk and recreates partitions,
				; which causes Windows to reassign the drive letter.  Refresh
				; $BootDir from the saved physical disk number ($INST_DISK) so
				; LABEL, CreateDirectory, and CopyFiles all target the correct letter.
				Call RefreshBootDirFromDisk																	 		   
				nsExec::Exec '"$SYSDIR\cmd.exe" /c LABEL $BootDir UUI'
				; If UUI directory doesn't exist, create it.
				${IfNot} ${FileExists} "$BootDir\UUI\*.*"
					CreateDirectory "$BootDir\UUI"
				${EndIf}
				; If ventoy directory doesn't exist, create it.
				${IfNot} ${FileExists} "$BootDir\ventoy\*.*"
					CreateDirectory "$BootDir\ventoy"
				${EndIf}
				; If ventoy/ventoy.json file doesn't exist, copy it over.
				${IfNot} ${FileExists} "$BootDir\ventoy\ventoy.json"
					CopyFiles "$PLUGINSDIR\ventoy.json" "$BootDir\ventoy\ventoy.json"
				${EndIf}
				; If ventoy/theme/UUI/theme.txt doesn't exist, copy it over.
				${IfNot} ${FileExists} "$BootDir\ventoy\theme\UUI\theme.txt"
					CreateDirectory "$BootDir\ventoy\theme"
					SetOutPath "$BootDir\ventoy\theme\"
					Nsis7z::ExtractWithDetails "$PLUGINSDIR\theme.7z" "Extracting UUI theme files %s..."
					SetOutPath "$PLUGINSDIR"
				${EndIf}
				MessageBox MB_ICONEXCLAMATION "SUCCESS! $BootDir (Disk $INST_DISK) has been prepared!$\r$\n$\r$\nUUI theme and configuration files have been installed along with the Ventoy $Ventoy_Version bootloader files.$\r$\n$\r$\nClick OK to return to UUI and continue from step 2."
				Delete "$PLUGINSDIR\ventoy-$Ventoy_Version\cli_done.txt"
				ShowWindow $Uninstaller 1 ; Re-enable Uninstaller option.
			${Else}
				MessageBox MB_ICONEXCLAMATION "WARNING! There was an error and $BootDir (Disk $INST_DISK) has NOT been prepared."
			${EndIf}
		${Else}
			MessageBox MB_ICONEXCLAMATION "Your computer must connected to the internet in order to fetch the download from GitHub."
		${EndIf}
		Call DrivesList ; refresh drives list - post install or update
		Call postSelectDrive
		skipprep:
	${EndIf}
FunctionEnd

Function preGetDiskVolumeName
	;pop $1 ; get parameter
	System::Alloc 1024 ; Allocate string body
	Pop $0 ; Get the allocated string's address
	!define GetVolumeInformation "Kernel32::GetVolumeInformation(t,t,i,*i,*i,*i,t,i) i"
	System::Call '${GetVolumeInformation}("$preJustDrive",.r0,1024,,,,,1024)' ;
	;Push $0 ; Push result
	${If} $0 != ""
		StrCpy $VolName "$0"
	${Else}
		StrCpy $VolName ""
	${EndIf}
FunctionEnd

Function GetDiskVolumeName
	;pop $1 ; get parameter
	System::Alloc 1024 ; Allocate string body
	Pop $0 ; Get the allocated string's address
	System::Call '${GetVolumeInformation}("$JustDrive",.r0,1024,,,,,1024)' ;
	;Push $0 ; Push result
	${If} $0 != ""
		StrCpy $VolName "$0"
	${Else}
		StrCpy $VolName ""
	${EndIf}
FunctionEnd

Function DiskSpace
	${DriveSpace} "$JustDrive" "/D=T /S=G" $1 ; used to find total space of each drive
	${If} $1 > "0"
		StrCpy $Capacity "$1GB"
	${Else}
		StrCpy $Capacity ""
	${EndIf}
FunctionEnd

Function preDiskSpace
	${DriveSpace} "$preJustDrive" "/D=T /S=G" $1 ; used to find total space of each drive
	${If} $1 > "0"
		StrCpy $Capacity "$1GB"
	${Else}
		StrCpy $Capacity ""
	${EndIf}
FunctionEnd

Function RemovableorNot
	StrCpy $1 ""
	; Check if the drive is removable (type 2) or fixed (type 3) - we want to skip other types.
	System::Call 'kernel32::GetDriveType(t"$preJustDrive")i.s'
	Pop $1
	${If} $1 == 2 ; show removable drives
	${OrIf} $1 == 3 ; show fixed drives
		StrCpy $Removable $1
	${EndIf}
FunctionEnd

Function DrivesList
	${If} $WINE == "WINE" ; Use WINE detected method
		StrCpy $JustDrive $9
		Call GetDiskVolumeName
		Call DiskSpace
		;Prevent System Drive from being selected
		StrCpy $7 $WINDIR 3
		${If} $9 != ""
		${AndIf} $9 != "$7"
		${AndIf} ${FileExists} "$9UUI\*.*"
			SendMessage $DestDriveTxt ${CB_ADDSTRING} 0 "STR:$9 $VolName $Capacity"
		${EndIf}
		Push 1 ; must push something - see GetDrives documentation
	${Else}
		SendMessage $DestDriveTxt ${CB_RESETCONTENT} 0 0 ; Reset List of devices
		ReadEnvStr $SysDrive "SYSTEMDRIVE" ; Find the SystemDrive
		StrCpy $SysDrive "$SysDrive\" ; add the trailing slash
		System::Call 'kernel32::GetLogicalDrives()i.r0'
		StrCpy $2 0
		StrCpy $4 65 ; 'A'
		; Initialize drive variables
		StrCpy $DiskNum ""
		StrCpy $AccumDrives ""
		StrCpy $preJustDrive ""
		StrCpy $HDD0 ""
		StrCpy $HDD1 ""
		StrCpy $HDD2 ""
		StrCpy $HDD3 ""
		StrCpy $HDD4 ""
		StrCpy $HDD5 ""
		StrCpy $HDD6 ""
		StrCpy $HDD7 ""
		StrCpy $HDD8 ""
		StrCpy $HDD9 ""
		StrCpy $HDD10 ""
		StrCpy $HDD11 ""
		StrCpy $HDD12 ""
		StrCpy $HDD13 ""
		StrCpy $HDD14 ""
		StrCpy $HDD15 ""
		StrCpy $HDD16 ""
		StrCpy $HDD17 ""
		StrCpy $HDD18 ""
		StrCpy $HDD19 ""
		StrCpy $HDD20 ""
		StrCpy $HDD21 ""
		StrCpy $HDD22 ""
		StrCpy $HDD23 ""
		StrCpy $HDD24 ""
		StrCpy $HDD25 ""
		StrCpy $HDD26 ""
		Loop:
			IntOp $3 $0 & 1
			${If} $3 <> 0 ; looping
				IntFmt $3 "%c:\" $4
				Call PopNum
				; Use a series of ElseIfs to assign drive letter to the appropriate variable
				${If} $DiskNum == 0
					StrCpy $HDD0 "$HDD0 $3"
				${ElseIf} $DiskNum == 1
					StrCpy $HDD1 "$HDD1 $3"
				${ElseIf} $DiskNum == 2
					StrCpy $HDD2 "$HDD2 $3"
				${ElseIf} $DiskNum == 3
					StrCpy $HDD3 "$HDD3 $3"
				${ElseIf} $DiskNum == 4
					StrCpy $HDD4 "$HDD4 $3"
				${ElseIf} $DiskNum == 5
					StrCpy $HDD5 "$HDD5 $3"
				${ElseIf} $DiskNum == 6
					StrCpy $HDD6 "$HDD6 $3"
				${ElseIf} $DiskNum == 7
					StrCpy $HDD7 "$HDD7 $3"
				${ElseIf} $DiskNum == 8
					StrCpy $HDD8 "$HDD8 $3"
				${ElseIf} $DiskNum == 9
					StrCpy $HDD9 "$HDD9 $3"
				${ElseIf} $DiskNum == 10
					StrCpy $HDD10 "$HDD10 $3"
				${ElseIf} $DiskNum == 11
					StrCpy $HDD11 "$HDD11 $3"
				${ElseIf} $DiskNum == 12
					StrCpy $HDD12 "$HDD12 $3"
				${ElseIf} $DiskNum == 13
					StrCpy $HDD13 "$HDD13 $3"
				${ElseIf} $DiskNum == 14
					StrCpy $HDD14 "$HDD14 $3"
				${ElseIf} $DiskNum == 15
					StrCpy $HDD15 "$HDD15 $3"
				${ElseIf} $DiskNum == 16
					StrCpy $HDD16 "$HDD16 $3"
				${ElseIf} $DiskNum == 17
					StrCpy $HDD17 "$HDD17 $3"
				${ElseIf} $DiskNum == 18
					StrCpy $HDD18 "$HDD18 $3"
				${ElseIf} $DiskNum == 19
					StrCpy $HDD19 "$HDD19 $3"
				${ElseIf} $DiskNum == 20
					StrCpy $HDD20 "$HDD20 $3"
				${ElseIf} $DiskNum == 21
					StrCpy $HDD21 "$HDD21 $3"
				${ElseIf} $DiskNum == 22
					StrCpy $HDD22 "$HDD22 $3"
				${ElseIf} $DiskNum == 23
					StrCpy $HDD23 "$HDD23 $3"
				${ElseIf} $DiskNum == 24
					StrCpy $HDD24 "$HDD24 $3"
				${ElseIf} $DiskNum == 25
					StrCpy $HDD25 "$HDD25 $3"
				${ElseIf} $DiskNum == 26
					StrCpy $HDD26 "$HDD26 $3"
				${EndIf} ; End Enumerate
			${EndIf} ; End looping
			IntOp $4 $4 + 1
			IntOp $0 $0 >> 1
			StrCmp $0 0 "" loop
		
		; accumulated drive numbers for each drive variable (HDD1 to HDD26)
		${If} $HDD0 != ""
			${Trim} $HDD0 " $HDD0"
			StrCpy $AccumDrives $HDD0
			Call FindDriveStuff
		${EndIf}
		${If} $HDD1 != ""
			${Trim} $HDD1 " $HDD1"
			StrCpy $AccumDrives $HDD1
			Call FindDriveStuff
		${EndIf}
		${If} $HDD2 != ""
			${Trim} $HDD2 " $HDD2"
			StrCpy $AccumDrives $HDD2
			Call FindDriveStuff
		${EndIf}
		${If} $HDD3 != ""
			${Trim} $HDD3 " $HDD3"
			StrCpy $AccumDrives $HDD3
			Call FindDriveStuff
		${EndIf}
		${If} $HDD4 != ""
			${Trim} $HDD4 " $HDD4"
			StrCpy $AccumDrives $HDD4
			Call FindDriveStuff
		${EndIf}
		${If} $HDD5 != ""
			${Trim} $HDD5 " $HDD5"
			StrCpy $AccumDrives $HDD5
			Call FindDriveStuff
		${EndIf}
		${If} $HDD6 != ""
			${Trim} $HDD6 " $HDD6"
			StrCpy $AccumDrives $HDD6
			Call FindDriveStuff
		${EndIf}
		${If} $HDD7 != ""
			${Trim} $HDD7 " $HDD7"
			StrCpy $AccumDrives $HDD7
			Call FindDriveStuff
		${EndIf}
		${If} $HDD8 != ""
			${Trim} $HDD8 " $HDD8"
			StrCpy $AccumDrives $HDD8
			Call FindDriveStuff
		${EndIf}
		${If} $HDD9 != ""
			${Trim} $HDD9 " $HDD9"
			StrCpy $AccumDrives $HDD9
			Call FindDriveStuff
		${EndIf}
		${If} $HDD10 != ""
			${Trim} $HDD10 " $HDD10"
			StrCpy $AccumDrives $HDD10
			Call FindDriveStuff
		${EndIf}
		${If} $HDD11 != ""
			${Trim} $HDD11 " $HDD11"
			StrCpy $AccumDrives $HDD11
			Call FindDriveStuff
		${EndIf}
		${If} $HDD12 != ""
			${Trim} $HDD12 " $HDD12"
			StrCpy $AccumDrives $HDD12
			Call FindDriveStuff
		${EndIf}
		${If} $HDD13 != ""
			${Trim} $HDD13 " $HDD13"
			StrCpy $AccumDrives $HDD13
			Call FindDriveStuff
		${EndIf}
		${If} $HDD14 != ""
			${Trim} $HDD14 " $HDD14"
			StrCpy $AccumDrives $HDD14
			Call FindDriveStuff
		${EndIf}
		${If} $HDD15 != ""
			${Trim} $HDD15 " $HDD15"
			StrCpy $AccumDrives $HDD15
			Call FindDriveStuff
		${EndIf}
		${If} $HDD16 != ""
			${Trim} $HDD16 " $HDD16"
			StrCpy $AccumDrives $HDD16
			Call FindDriveStuff
		${EndIf}
		${If} $HDD17 != ""
			${Trim} $HDD17 " $HDD17"
			StrCpy $AccumDrives $HDD17
			Call FindDriveStuff
		${EndIf}
		${If} $HDD18 != ""
			${Trim} $HDD18 " $HDD18"
			StrCpy $AccumDrives $HDD18
			Call FindDriveStuff
		${EndIf}
		${If} $HDD19 != ""
			${Trim} $HDD19 " $HDD19"
			StrCpy $AccumDrives $HDD19
			Call FindDriveStuff
		${EndIf}
		${If} $HDD20 != ""
			${Trim} $HDD20 " $HDD20"
			StrCpy $AccumDrives $HDD20
			Call FindDriveStuff
		${EndIf}
		${If} $HDD21 != ""
			${Trim} $HDD21 " $HDD21"
			StrCpy $AccumDrives $HDD21
			Call FindDriveStuff
		${EndIf}
		${If} $HDD22 != ""
			${Trim} $HDD22 " $HDD22"
			StrCpy $AccumDrives $HDD22
			Call FindDriveStuff
		${EndIf}
		${If} $HDD23 != ""
			${Trim} $HDD23 " $HDD23"
			StrCpy $AccumDrives $HDD23
			Call FindDriveStuff
		${EndIf}
		${If} $HDD24 != ""
			${Trim} $HDD24 " $HDD24"
			StrCpy $AccumDrives $HDD24
			Call FindDriveStuff
		${EndIf}
		${If} $HDD25 != ""
			${Trim} $HDD25 " $HDD25"
			StrCpy $AccumDrives $HDD25
			Call FindDriveStuff
		${EndIf}
		${If} $HDD26 != ""
			${Trim} $HDD26 " $HDD26"
			StrCpy $AccumDrives $HDD26
			Call FindDriveStuff
		${EndIf}
	${EndIf} ; EndIf WINE detected
FunctionEnd

; ---------------------------------------------------------------------------
; WipeDrive
; Wipes the selected disk using diskpart: clean, create primary partition,
; format exFAT quick, set active, assign drive letter, then refreshes
; $BootDir via RefreshBootDirFromDisk so subsequent operations use the
; correct letter.  Safety guards mirror those used in ExecFAT.
; ---------------------------------------------------------------------------
Function WipeDrive
	; Require a drive to be selected
	${If} $DestDrive == ""
		MessageBox MB_ICONEXCLAMATION "Please select a USB device first (Step 1)."
		Return
	${EndIf}

	; Guard: never wipe the system drive
	${If} "$JustDrive" == "$SysDrive"
		MessageBox MB_ICONSTOP "Cannot wipe ($DestDisk) - it appears to be the booted system drive."
		Return
	${EndIf}

	; Guard: never wipe a drive containing a Windows system directory
	${If} ${FileExists} "$BootDir\windows\system32"
		MessageBox MB_ICONSTOP "Cannot wipe ($DestDisk) - it contains a Windows\System32 directory."
		Return
	${EndIf}

	; Guard: never wipe a drive containing an excludedrive.txt marker
	${If} ${FileExists} "$BootDir\excludedrive.txt"
		MessageBox MB_ICONSTOP "Cannot wipe ($DestDisk) - an excludedrive.txt marker was found on this drive."
		Return
	${EndIf}

	; Confirm with the user
	MessageBox MB_YESNO|MB_ICONEXCLAMATION \
		"You selected ($DestDisk) on (Disk $DiskNum)$\r$\n$\r$\n\
		=============== WARNING! ===============$\r$\n$\r$\n\
		This will IRRECOVERABLY wipe all data on (Disk $DiskNum),$\r$\n\
		including all partitions and volumes, even hidden ones.$\r$\n$\r$\n\
		The following diskpart commands will run:$\r$\n\
		  select disk $DiskNum$\r$\n\
		  clean$\r$\n\
		  create partition primary$\r$\n\
		  format fs=exfat quick label=UUI$\r$\n\
		  active$\r$\n\
		  assign letter=$DestDisk$\r$\n\
		  exit$\r$\n$\r$\n\
		Verify (Disk $DiskNum) in Windows Disk Management before proceeding.$\r$\n$\r$\n\
		Click YES to wipe and format, or NO to abort." \
		IDYES wipe_confirmed
	Return  ; user clicked NO

wipe_confirmed:
	; Save disk number now - DrivesList (called below on success) resets $DiskNum
	; to the last-enumerated disk, so we must anchor to $INST_DISK before that.
	StrCpy $INST_DISK "$DiskNum"

	; Build the diskpart script in PLUGINSDIR.
	; Template tokens: DISKNUM -> physical disk number
	;                  DSK     -> drive letter only (no colon; diskpart wants "assign letter=E")
	;                  LBL     -> volume label
	StrCpy $WipeDiskpartScript "$PLUGINSDIR\wipedrive.txt"
	CopyFiles "$PLUGINSDIR\diskpartwipe.txt" "$WipeDiskpartScript"
	!insertmacro ReplaceInFile "DISKNUM" "$DiskNum" "all" "all" "$WipeDiskpartScript"
	; Strip the trailing colon from $DestDisk (e.g. "E:" -> "E") for "assign letter=E"
	StrCpy $R0 $DestDisk 1   ; just the bare letter, no colon
	!insertmacro ReplaceInFile "DSK" "$R0" "all" "all" "$WipeDiskpartScript"
	!insertmacro ReplaceInFile "LBL" "USB" "all" "all" "$WipeDiskpartScript"

	Banner::show /set 76 "Wiping and formatting drive. Please wait..."
	nsExec::ExecToLog 'DiskPart /S "$WipeDiskpartScript"'
	Pop $0  ; diskpart return code
	Banner::destroy

	Delete "$WipeDiskpartScript"

	${If} $0 == 0
		; Diskpart succeeded - drive letter may have changed.
		; RefreshBootDirFromDisk uses $INST_DISK (saved above) so it survives
		; the DrivesList call that resets $DiskNum.
		Call RefreshBootDirFromDisk
		Call DrivesList
		Call postSelectDrive
		MessageBox MB_ICONINFORMATION \
			"(Disk $INST_DISK) has been wiped and exFAT formatted as one partition.$\r$\n$\r$\n\
			Drive letter is now: $BootDir$\r$\n$\r$\n\
			You may now reinstall or just exit the program."
	${Else}
		MessageBox MB_ICONSTOP \
			"DiskPart returned error code $0.$\r$\n$\r$\n\
			The wipe did not complete successfully.$\r$\n\
			Check that UUI is running as Administrator."
	${EndIf}
FunctionEnd
; ---------------------------------------------------------------------------
; RefreshBootDirFromDisk
; Ventoy's fresh install wipes and recreates partitions, causing Windows to
; reassign the drive letter.  This function re-scans logical drives, finds
; the first letter belonging to the saved physical disk ($INST_DISK), and
; updates $BootDir / $DestDrive / $JustDrive / $DestDisk accordingly.
; ---------------------------------------------------------------------------
Function RefreshBootDirFromDisk
	; Rebuild the HDD0..HDD26 drive-to-physicaldisk maps.
	Call DrivesList

	; NSIS has no indirect variable access, so use an if/elseif ladder
	; (same pattern already used throughout DrivesList).
	StrCpy $AccumDrives ""
	${If}     $INST_DISK == 0
		StrCpy $AccumDrives $HDD0
	${ElseIf} $INST_DISK == 1
		StrCpy $AccumDrives $HDD1
	${ElseIf} $INST_DISK == 2
		StrCpy $AccumDrives $HDD2
	${ElseIf} $INST_DISK == 3
		StrCpy $AccumDrives $HDD3
	${ElseIf} $INST_DISK == 4
		StrCpy $AccumDrives $HDD4
	${ElseIf} $INST_DISK == 5
		StrCpy $AccumDrives $HDD5
	${ElseIf} $INST_DISK == 6
		StrCpy $AccumDrives $HDD6
	${ElseIf} $INST_DISK == 7
		StrCpy $AccumDrives $HDD7
	${ElseIf} $INST_DISK == 8
		StrCpy $AccumDrives $HDD8
	${ElseIf} $INST_DISK == 9
		StrCpy $AccumDrives $HDD9
	${ElseIf} $INST_DISK == 10
		StrCpy $AccumDrives $HDD10
	${ElseIf} $INST_DISK == 11
		StrCpy $AccumDrives $HDD11
	${ElseIf} $INST_DISK == 12
		StrCpy $AccumDrives $HDD12
	${ElseIf} $INST_DISK == 13
		StrCpy $AccumDrives $HDD13
	${ElseIf} $INST_DISK == 14
		StrCpy $AccumDrives $HDD14
	${ElseIf} $INST_DISK == 15
		StrCpy $AccumDrives $HDD15
	${ElseIf} $INST_DISK == 16
		StrCpy $AccumDrives $HDD16
	${ElseIf} $INST_DISK == 17
		StrCpy $AccumDrives $HDD17
	${ElseIf} $INST_DISK == 18
		StrCpy $AccumDrives $HDD18
	${ElseIf} $INST_DISK == 19
		StrCpy $AccumDrives $HDD19
	${ElseIf} $INST_DISK == 20
		StrCpy $AccumDrives $HDD20
	${ElseIf} $INST_DISK == 21
		StrCpy $AccumDrives $HDD21
	${ElseIf} $INST_DISK == 22
		StrCpy $AccumDrives $HDD22
	${ElseIf} $INST_DISK == 23
		StrCpy $AccumDrives $HDD23
	${ElseIf} $INST_DISK == 24
		StrCpy $AccumDrives $HDD24
	${ElseIf} $INST_DISK == 25
		StrCpy $AccumDrives $HDD25
	${ElseIf} $INST_DISK == 26
		StrCpy $AccumDrives $HDD26
	${EndIf}

	; $AccumDrives is a space-separated list of drive letters on this disk,
	; e.g. "F:\ G:\ ".  The first token is the main data partition.
	${If} $AccumDrives != ""
		${Trim} $AccumDrives " $AccumDrives"  ; strip leading space
		StrCpy $0 $AccumDrives 3              ; grab "X:\" (first letter)
		StrCpy $BootDir   $0 2               ; "X:"
		StrCpy $DestDrive $0 2
		StrCpy $JustDrive $0 3               ; "X:\"
		StrCpy $DestDisk  $0 2
	${EndIf}
FunctionEnd																			 

Function WhatDrives
	; Prevent Drives with a Windows System directory from being selected
	StrCpy $7 $WINDIR 3
	${If} $preJustDrive != "$7" ; Start conditional devices to skip
	${AndIf} "$preJustDrive" != "$SysDrive" ; System Drive detection method replaces Disk 0 method
	${AndIfNot} ${FileExists} "$preJustDrivewindows\system32" ; additional safeguard to help protect from mishap.
	${AndIfNot} ${FileExists} "$preJustDrive\excludedrive.txt" ; text file that can be added to a drive to prevent it from appearing.
		${If} $RepeatInstall == "YES" ; Repeat Install Option is YES
		${OrIf} $Removal == "YES"
			${If} $Removable == 2 ; show removable devices
			${OrIf} $Removable == 3 ; show fixed devices too
			${AndIf} ${FileExists} "$preJustDriveUUI\*" ; Only display devices that are prepared
				;MessageBox MB_OK "$preJustDriveUUI\*"
				Goto Enumerate
			${EndIf}
		${EndIf} ; End for RepeatInstall
		${If} $RepeatInstall != "YES"
		${AndIf} $Removal != "YES"
			${If} $Removable == 2 ; show removable devices
			${OrIf} $Removable == 3 ; show fixed devices too
				Goto Enumerate
			${EndIf}
		${EndIf} ; End for ShowAll Drives
		Goto SkipEnumerate
		Enumerate:
			SendMessage $DestDriveTxt ${CB_ADDSTRING} 0 "STR:$AccumDrives (Disk $DiskNum) $Capacity $VolName" ; $ProdId
		SkipEnumerate:
	${EndIf} ; End conditional devices to skip
FunctionEnd

Function FindDriveStuff
	StrCpy $preJustDrive $AccumDrives 3
	Call RemovableorNot
	Call prePhysDrive
	Call preGetDiskVolumeName
	Call preDiskSpace
	Call GetFSType
	Call WhatDrives ; which drives to display?
FunctionEnd

Function FormatYES ; If Format is checked, do something
	${If} $FormatChoice == "YES"
		SetShellVarContext all
		InitPluginsDir
	${Endif}
FunctionEnd

Function FormatIt ; Set Format Option
	${NSD_GetState} $Format $FormatMe
	${If} $FormatMe == ${BST_CHECKED}
		${NSD_Check} $Format
		StrCpy $FormatChoice "YES"
		SendMessage $Distro ${CB_RESETCONTENT} 0 0 ; Clear all distro entries because a new format option may have been chosen ; Enable for DropBox
		ShowWindow $Uninstaller 0 ; Disable Uninstaller option because we will be formatting the drive.
		StrCpy $Checker "YES"
		${If} $ReUpdate == "NO" ; Fresh Install - So Initialize VentoyOptionsDialog
			Call VentoyOptionsDialog
			StrCpy $VENTOY_ACTIVE 1
			Call HideSelectionsUI
			Call HideISOControls
			Call ShowVentoyUI
		${Endif}
		${If} $ReUpdate == "YES" ; It's an Update/Version Reinstall
			StrCpy $VENTOY_ACTIVE 0
			Call HideVentoyUI
			Call ShowSelectionsUI
			Call ExecFAT ; Calling to run the Update/Reinstall option in ExecFAT
		${Endif}
		${NSD_Uncheck} $Format
	${ElseIf} $FormatMe == ${BST_UNCHECKED}
		${NSD_Uncheck} $Format
		StrCpy $FormatChoice ""
		StrCpy $VENTOY_ACTIVE 0
		Call HideVentoyUI
		Call ShowSelectionsUI
		;Call RefreshUI
		SendMessage $Distro ${CB_RESETCONTENT} 0 0 ; Clear all distro entries because a new format option may have been chosen ; Enable for DropBox
		${If} ${FileExists} "$BootDir\UUI\*"
			ShowWindow $Uninstaller 1 ; Re-enable Uninstaller option.
			${If} $WINE != "WINE" ; IfNot WINE detection method
				EnableWindow $Format 1
				ShowWindow $Format 1
			${EndIf} ; EndIf Not WINE
			; ShowWindow $Wipe 1
		${EndIf}
		StrCpy $Checker "YES"
		Call SetSpace
	${EndIf}
	Call InstallorRemove
FunctionEnd

Function ShowAllISOs ; Set Show All ISOs Option
	${NSD_GetState} $ForceShowAll $ShowingAll
	${If} $ShowingAll == ${BST_CHECKED}
		${NSD_Check} $ForceShowAll
		StrCpy $ShowingAll "YES"
		${NSD_SetText} $ForceShowAll "Show All ISOs!"
		SendMessage $ISOSelection ${CB_RESETCONTENT} 0 0
	${ElseIf} $ShowingAll == ${BST_UNCHECKED}
		${NSD_Uncheck} $ForceShowAll
		${NSD_SetText} $ForceShowAll "Show All ISOs?"
		SendMessage $ISOSelection ${CB_RESETCONTENT} 0 0
	${EndIf}
FunctionEnd

Function CheckSpace ; Check total available space so we can set block size
	Call TotalSpace
	${If} $1 <= 511
		StrCpy $BlockSize 1
	${ElseIf} $1 >= 512
	${AndIf} $1 <= 8191
		StrCpy $BlockSize 4
	${ElseIf} $1 >= 8192
	${AndIf} $1 <= 16383
		StrCpy $BlockSize 8
	${ElseIf} $1 >= 16384
	${AndIf} $1 <= 32767
		StrCpy $BlockSize 16
	${ElseIf} $1 > 32768
		StrCpy $BlockSize 32
	${EndIf}
FunctionEnd

Function TotalSpace
	${DriveSpace} "$JustDrive" "/D=T /S=M" $1 ; used to find total space of select disk
	StrCpy $Capacity "$1"
FunctionEnd

Function FreeDiskSpace
	${DriveSpace} "$JustDrive" "/D=F /S=M" $1
FunctionEnd

Function SetSpace ; Set space available for persistence
	Call FreeDiskSpace
	StrCpy $RemainingSpace "$1"
	IntOp $RemainingSpace $RemainingSpace - $SizeOfCasper ; Subtract ISO Size
	IntOp $RemainingSpace $RemainingSpace - 10 ; Subtract 10MB as a buffer
	${If} $DistroName == "Phoenix LiteOS"
	${OrIf} $DistroName == "Windows X-Lite"
		SendMessage $CasperSlider ${TBM_SETRANGEMAX} 1 $RemainingSpace ; Re-Setting Max Value
	${Else}
		${If} $RemainingSpace >= "40000" ; max 40GB Casper File even if more space on disk
			SendMessage $CasperSlider ${TBM_SETRANGEMAX} 1 "40000" ; Re-Setting Max to 40GB
		${Else}
			SendMessage $CasperSlider ${TBM_SETRANGEMAX} 1 $RemainingSpace ; Re-Setting Max Value
		${EndIf}
	${EndIf}
FunctionEnd

Function HaveSpacePre ; Check space required
	Call CasperSize
	Call FreeDiskSpace
	System::Int64Op $1 > $SizeOfCasper ; Compare the space available > space required
	Pop $3 ; Get the result ...
	IntCmp $3 1 okay ; ... and compare it
	MessageBox MB_ICONSTOP|MB_OK "Oops: There is not enough disk space! on $JustDrive Drive for $JustISO.$\r$\n$\r$\n($1) MB Free$\r$\n$\r$\n($SizeOfCasper) MB Needed$\r$\n$\r$\nNOTE: If this tool is showing () MB Free, you may need to Wipe and Format your Disk? This tool can do this for you by choosing the option to 'Prepare this Disk'. It's also possible that it isn't being read correctly. In which case, refreshing the drive list might help."
	Call NoSpace
	okay: ; Proceed to execute...
FunctionEnd

Function HaveSpace ; Check space required
	Call CasperSize
	Call FreeDiskSpace
	System::Int64Op $1 > $SizeOfCasper ; Compare the space available > space required
	Pop $3 ; Get the result ...
	IntCmp $3 1 okay ; ... and compare it
	MessageBox MB_ICONSTOP|MB_OK "Not enough free space remains. Please free up disk space and try again. Aborting!"
	Quit ; Close the program if the disk space was too small...
	okay: ; Proceed to execute...
FunctionEnd

; Custom Distros Installer - Uninstaller Include
!include "InstallDistro.nsh" ; ##################################### Add DISTRO ########################################
!include "RemoveDistro.nsh" ; ##################################### Remove DISTRO ########################################

; ---- Let's Do This Stuff ----
Section  ; This is the only section that exists
	; Get just the name of the ISO file
	Push "$ISOFile"
	Push 1
	Call GrabNameOnly
	Pop $NameThatISO
	
	; Prevent from installing on booted drive.
	;${If} $DiskNum == "0"
	${If} "$JustDrive" == "$SysDrive"
		MessageBox MB_ICONEXCLAMATION|MB_OK "Will not attempt to install on ($SysDrive) which appears to be the booted system drive." ;(Disk $DiskNum)
		Quit
	${EndIf}
	
	; Make sure drive doesn't contain Windows... (secondary check - the droplist shouldn't be displaying Windows System drives).
	${If} ${FileExists} "$BootDir\windows\system32" ; additional safeguard to help protect from mishap.
		MessageBox MB_ICONSTOP|MB_OK "ABORTING! ($DestDisk) contains a WINDOWS/SYSTEM32 Directory."
		Quit
	${EndIf}
	
	Call GetFSType
	;checkpoint:
	;proceed:
	${IfThen} $Removal == "YES" ${|} Goto removeonly ${|}
	
	Call HaveSpace ; Got enough Space? Lets Check!
	Call FormatYES ; Format the Drive?
	;Goto theend ; Temporary test stop here.
	Call LocalISODetected
	
	; If path doesn't exist, create the directory.
	${IfNot} ${FileExists} "$BootDir\UUI\$DistroPath\*.*"
		CreateDirectory "$BootDir\UUI\$DistroPath"
	${EndIf}
	
	; If ventoy directory doesn't exist, create it.
	${IfNot} ${FileExists} "$BootDir\ventoy\*.*"
		CreateDirectory "$BootDir\ventoy"
	${EndIf}
	
	; If ventoy/ventoy.json file doesn't exist, copy it over.
	${IfNot} ${FileExists} "$BootDir\ventoy\ventoy.json"
		CopyFiles "$PLUGINSDIR\ventoy.json" "$BootDir\ventoy\ventoy.json"
	${EndIf}
	
	; If ventoy/theme/UUI/theme.txt doesn't exist, copy it over.
	${IfNot} ${FileExists} "$BootDir\ventoy\theme\UUI\theme.txt"
		CreateDirectory "$BootDir\ventoy\theme"
		SetOutPath "$BootDir\ventoy\theme\"
		Nsis7z::ExtractWithDetails "$PLUGINSDIR\theme.7z" "Extracting UUI theme files %s..."
		SetOutPath "$PLUGINSDIR"
	${EndIf}
	
	removeonly:
	${If} $Removal != "YES"
		!insertmacro Install_Distros ; Install those distros
	${ElseIf} $Removal == "YES"
		!insertmacro Uninstall_Distros ; Remove those distros
	${EndIf}
	;theend:
SectionEnd

Function NoQuit
	MessageBox MB_YESNO "Would you like to add more ISOs/Distros Now on $DestDisk?" IDYES noskip
	StrCmp $R8 3 0 End ;Compare $R8 variable with current page #
	StrCpy $R9 1 ; Goes to finish page
	Call RelGotoPage
	Abort
	noskip:
		StrCpy $ShowAll "YES" ; Display All Drives
		StrCpy $DestDrive "$DestDrive" ; Retain previously selected Drive Letter
		StrCpy $DiskNum "$DiskNum" ; Retain previously selected Disk
		StrCpy $VolName $VolName
		StrCpy $FSType $FSType
		StrCpy $BOOT_DISK "$BOOT_DISK" ; Retain previously selected Disk
		;StrCpy $DiskNum "$BOOT_DISK" ; Retain previously selected Disk
		StrCpy $RepeatInstall "YES" ; Set Repeat Install Option to YES
		StrCpy $ISOTest "" ; Reset
		StrCpy $JustISO "" ; Reset
		StrCpy $JustISOName "" ; Reset
		StrCpy $ISOFile "" ; Reset
		StrCpy $Removal "" ; Reset
		StrCpy $Persistence "NULL" ; Reset
		StrCpy $NameThatISO "" ; Reset NameThatISO ISO Name
		StrCpy $DistroPath "" ; Clear Path to create
		StrCpy $DistroName "" ; Clear Distro Name
		StrCpy $ISOFileName "" ; Clear ISO Selection
		StrCpy $FileFormat "" ; Clear File Format
		StrCpy $DownloadMe 0 ; Ensure Uncheck of Download Option
		StrCpy $LocalSelection "" ; Reset Local Selection
		StrCpy $ShowingAll ""
		StrCpy $FormatChoice "" ; Reset Format Option
		StrCmp $R8 4 0 End ;Compare $R8 variable with current page #
		StrCpy $R9 -3 ; Goes back to selections page
		
 /*  ; Hide or disable steps again until we state to display them
	EnableWindow $LabelISOSelection 0 ; disabled until step 2 is done
	EnableWindow $ISOFileTxt 0 ; disabled until step 2 is done	
	ShowWindow $ISOSelection 0
	EnableWindow $LinuxDistroSelection 0
	EnableWindow $Distro 0
	EnableWindow $DownloadISO 0
	ShowWindow $DistroLink 0
	ShowWindow $CasperSelection 0
	ShowWindow $CasperSlider 0
	ShowWindow $SlideSpot 0
	ShowWindow $Format 0
	ShowWindow $ForceShowAll 0
	ShowWindow $Uninstaller 0
	ShowWindow $CasperSelection1 0
	ShowWindow $CasperSlider1 0
	ShowWindow $SlideSpot1 0
	Call EnableNext  */		
		
		Call RelGotoPage ; change pages
		Abort
	End:
FunctionEnd

Function RelGotoPage
	IntCmp $R9 0 0 Move Move
	StrCmp $R9 "X" 0 Move
	StrCpy $R9 "120"
	Move:
		SendMessage $HWNDPARENT "0x408" "$R9" ""
FunctionEnd

; --- Stuff to do at startup of script ---
Function .onInit
	; Call Checker ; Checks for version changes ~ enable for auto checker at startup
	StrCpy $RecentVersionDisplay "YES" ; initates after init
	StrCpy $R9 0 ; we start on page 0
	;StrCpy $InstallButton ""
	StrCpy $FileFormat "ISO"
	userInfo::getAccountType
	Pop $Auth
	strCmp $Auth "Admin" done
	Messagebox MB_OK|MB_ICONINFORMATION "Currently you're trying to run this program as: $Auth$\r$\n$\r$\nYou must run this program with administrative rights...$\r$\n$\r$\nRight click the file and select Run As Administrator or Run As (and select an administrative account)!"
	Abort
	done:
		SetShellVarContext all
		InitPluginsDir
		File /oname=$PLUGINSDIR\ventoy-windows.zip "tools\ventoy*windows.zip"
		File /oname=$PLUGINSDIR\UUI-EXFAT "tools\UUI-EXFAT"
		File /oname=$PLUGINSDIR\UUI-Copying.txt "UUI-Copying.txt"
		File /oname=$PLUGINSDIR\license.txt "license.txt"
		File /oname=$PLUGINSDIR\w2gdiskpart.txt "w2gdiskpart.txt"
		File /oname=$PLUGINSDIR\diskpartdetach.txt "diskpartdetach.txt"
		File /oname=$PLUGINSDIR\diskpartwipe.txt "diskpartwipe.txt"															 
		File /oname=$PLUGINSDIR\dskvol.txt "dskvol.txt"
		File /oname=$PLUGINSDIR\dismstuff.cmd "dismstuff.cmd"
		File /oname=$PLUGINSDIR\7zG.exe "tools\7zG.exe"
		File /oname=$PLUGINSDIR\7z.dll "tools\7z.dll"
		File /oname=$PLUGINSDIR\AutoUnattend.xml "AutoUnattend.xml"
		File /oname=$PLUGINSDIR\ventoy.json "ventoy.json"
		File /oname=$PLUGINSDIR\theme.7z "theme.7z"
		SetOutPath "$PLUGINSDIR"
		File /r "wimlib"
		SetOutPath ""
		ClearErrors
		# check for WINE in registry
		EnumRegKey $0 HKLM "Software\Wine" 0
		IfErrors 0 wine
		StrCpy $WINE "NULL" ; WINE Does Not Exist
		Goto notwine
	wine:
		StrCpy $WINE "WINE"
		; Messagebox MB_OK|MB_ICONINFORMATION "This program appears to be running from $WINE.$\r$\n$\r$\nThis is fine as long as your USB drive has already been prepared for UUI.$\r$\n$\r$\nThe prep and format features and Windows distro options do not currently work from WINE."
	notwine:
FunctionEnd

Function onNotify_CasperSlider
	Pop $Casper
	SendMessage $CasperSlider ${TBM_GETPOS} 0 0 $Casper ; Get position
	${NSD_SetText} $SlideSpot "$Casper MB"
FunctionEnd

Function onNotify_CasperSlider1
	Pop $Casper
	SendMessage $CasperSlider1 ${TBM_GETPOS} 0 0 $Casper
	${If} $Casper == 0
		StrCpy $CasperFile ""
		StrCpy $CasperSizeText "None"
		StrCpy $CasperURL ""
	${ElseIf} $Casper == 1
		StrCpy $CasperFile "8gpersistence.zip"
		StrCpy $CasperSizeText "8GB"
		StrCpy $CasperURL "$PLUGINSDIR/8gpersistence.zip" ;"https://pendrivelinux.com/downloads/8gpersistence.zip"
	${ElseIf} $Casper == 2
		StrCpy $CasperFile "16gpersistence.zip"
		StrCpy $CasperSizeText "16GB"
		StrCpy $CasperURL "$PLUGINSDIR/16gpersistence.zip" ;"https://pendrivelinux.com/downloads/16gpersistence.zip"
	${ElseIf} $Casper == 3
		StrCpy $CasperFile "32gpersistence.zip"
		StrCpy $CasperSizeText "32GB"
		StrCpy $CasperURL "$PLUGINSDIR/32gpersistence.zip" ;"https://pendrivelinux.com/downloads/32gpersistence.zip"
	${EndIf}
	${NSD_SetText} $SlideSpot1 "Persistence: $CasperSizeText"
FunctionEnd

Function SetISOSize ; Get size of ISO
	System::Call 'kernel32::CreateFile(t "$TheISO", i 0x80000000, i 1, i 0, i 3, i 0, i 0) i .r0'
	System::Call "kernel32::GetFileSizeEx(i r0, *l .r1) i .r2"
	System::Alloc $1
	System::Int64Op $1 / 1048576 ; convert to MB
	Pop $1
	StrCpy $SizeOfCasper "$1"
	; MessageBox MB_OK|MB_ICONINFORMATION "ISO Size: $SizeOfCasper"
	System::Call 'kernel32::CloseHandle(i r0)'
FunctionEnd

Function GetFSType
	System::Call 'Kernel32::GetVolumeInformation(t "$JustDrive",t,i ${NSIS_MAX_STRLEN},*i,*i,*i,t .r1",i ${NSIS_MAX_STRLEN}) i.r0'
	StrCpy $FSType "$1"
FunctionEnd

Function VentoyOptionsDialog
	${NSD_CreateLabel} 0 0 100% 12u "Format Options"
	Pop $VTOY_LABEL
	
	${NSD_CreateCheckbox} 0 18u 50% 12u "Use GPT partition style"
	Pop $VTOY_GPT
	
	${NSD_CreateCheckbox} 0 36u 50% 12u "Disable Secure Boot support"
	Pop $VTOY_NOSB
	
	${NSD_CreateCheckbox} 0 54u 50% 12u "Non destructive install"
	Pop $VTOY_NONDEST
	
	${NSD_CreateLabel} 0 76u 50% 12u "Storage Filesystem:"
	Pop $VTOY_FS_LABEL
	
	${NSD_CreateDropList} 50% 74u 50% 80u ""
	Pop $VTOY_FS_CTL
	${NSD_CB_AddString} $VTOY_FS_CTL "NTFS"
	${NSD_CB_AddString} $VTOY_FS_CTL "EXFAT"
	${NSD_CB_AddString} $VTOY_FS_CTL "FAT32"
	${NSD_CB_SelectString} $VTOY_FS_CTL "EXFAT"
	
	${NSD_CreateLabel} 0 102u 50% 12u "Reserve space at end of disk (MB):"
	Pop $VTOY_RESERVE_LABEL
	
	${NSD_CreateText} 50% 100u 50% 12u "0"
	Pop $VTOY_RESERVE
	
	; informational label in the mid right empty space
	${NSD_CreateLabel} 50% 20u 50% 40u "These are additional install options. You can learn more about them on the project page.$\r$\n$\r$\nJust click 'Confirm and Format' to wipe, format, and prepare (Disk $DiskNum) with the defaults."
	Pop $VTOY_INFO
	
	${NSD_CreateButton} 60% 122u 40% 18u "Confirm and Format"
	Pop $VTOY_CONFIRM
	${NSD_OnClick} $VTOY_CONFIRM OnVentoyConfirm
FunctionEnd

Function ShowVentoyUI
	ShowWindow $VTOY_LABEL 1
	EnableWindow $VTOY_GPT 0 ; This feature isn't working yet.
	ShowWindow $VTOY_GPT 1
	ShowWindow $VTOY_NOSB 1
    EnableWindow $VTOY_NONDEST 0 ; This feature isn't working yet.
	ShowWindow $VTOY_NONDEST 1
	ShowWindow $VTOY_FS_LABEL 1
	ShowWindow $VTOY_FS_CTL 1
	ShowWindow $VTOY_RESERVE_LABEL 1
	ShowWindow $VTOY_RESERVE 1
	ShowWindow $VTOY_CONFIRM 1
	ShowWindow $VTOY_INFO 1
FunctionEnd

Function HideVentoyUI
	ShowWindow $VTOY_LABEL 0
	ShowWindow $VTOY_GPT 0
	ShowWindow $VTOY_NOSB 0
	ShowWindow $VTOY_NONDEST 0
	ShowWindow $VTOY_FS_LABEL 0
	ShowWindow $VTOY_FS_CTL 0
	ShowWindow $VTOY_RESERVE_LABEL 0
	ShowWindow $VTOY_RESERVE 0
	ShowWindow $VTOY_CONFIRM 0
	ShowWindow $VTOY_INFO 0
FunctionEnd

Function OnVentoyConfirm
	; 1. Read Ventoy option states
	${NSD_GetState} $VTOY_GPT $VTOY_GPT_STATE
	${NSD_GetState} $VTOY_NOSB $VTOY_NOSB_STATE
	${NSD_GetState} $VTOY_NONDEST $VTOY_NONDEST_STATE
	${NSD_GetText} $VTOY_FS_CTL $VTOY_FS_VAL
	${NSD_GetText} $VTOY_RESERVE $VTOY_RESERVE_VAL
	
	; Build Ventoy CLI args
	Call BuildVentoyArgs
	;MessageBox MB_ICONINFORMATION "Ventoy config args:$\r$\n$VTOY_ARGS"
	
	; Hide Ventoy options UI
	Call HideVentoyUI
	
	; Restore main UI
	Call ShowSelectionsUI
	
	; Re evaluate Casper visibility ONCE
	;Call UpdateCasperUI
	
	; Lock format so user cannot re-toggle
	EnableWindow $Format 0
	
	; Proceed with execution
	Call ExecFAT
FunctionEnd

Function BuildVentoyArgs
	StrCpy $VTOY_ARGS ""
	${If} $VTOY_GPT_STATE == ${BST_CHECKED}
		StrCpy $VTOY_ARGS "$VTOY_ARGS /GPT"
	${EndIf}
	${If} $VTOY_NOSB_STATE == ${BST_CHECKED}
		StrCpy $VTOY_ARGS "$VTOY_ARGS /NOSB"
	${EndIf}
	${If} $VTOY_NONDEST_STATE == ${BST_CHECKED}
		StrCpy $VTOY_ARGS "$VTOY_ARGS /ND"
	${EndIf}
	${If} "$VTOY_FS_VAL" != ""
		StrCpy $VTOY_ARGS "$VTOY_ARGS /FS:$VTOY_FS_VAL"
	${EndIf}
	${If} "$VTOY_RESERVE_VAL" != "0"
		StrCpy $VTOY_ARGS "$VTOY_ARGS /R:$VTOY_RESERVE_VAL"
	${EndIf}
FunctionEnd

Function HideSelectionsUI
	ShowWindow $AllDriveOption 0
	;Call RefreshUI
	ShowWindow $LinuxDistroSelection 0
	ShowWindow $Distro 0
	ShowWindow $ForceShowAll 0
	ShowWindow $DownloadISO 0
	ShowWindow $DistroLink 0
	ShowWindow $LabelISOSelection 0
	ShowWindow $ISOFileTxt 0
	ShowWindow $ISOSelection 0
	ShowWindow $LabelDrivePage 0
	ShowWindow $DestDriveTxt 0
	ShowWindow $Wipe 0
	ShowWindow $Link2 0
	ShowWindow $VersionChk 0
	ShowWindow $Format 0
FunctionEnd

Function ShowSelectionsUI
	ShowWindow $AllDriveOption 1
	ShowWindow $LinuxDistroSelection 1
	ShowWindow $Distro 1
	ShowWindow $LabelDrivePage 1
	ShowWindow $DestDriveTxt 1
	ShowWindow $Format 1
	ShowWindow $LabelISOSelection 1
	ShowWindow $ISOFileTxt 1
	; Only show ISO-related controls if a distro is selected
	${If} $DistroName != ""
		ShowWindow $ForceShowAll 1
		ShowWindow $DownloadISO 1
		ShowWindow $DistroLink 1
		ShowWindow $ISOSelection 1
	${Else}
		ShowWindow $ForceShowAll 0
		ShowWindow $DownloadISO 0
		ShowWindow $DistroLink 0
		ShowWindow $ISOSelection 0
	${EndIf}
	ShowWindow $Wipe 1
	ShowWindow $Link2 1
	ShowWindow $VersionChk 1
FunctionEnd

Function HideISOControls
	ShowWindow $ISOSelection 0
	ShowWindow $ForceShowAll 0
	ShowWindow $DistroLink 0
	EnableWindow $ISOFileTxt 0
	EnableWindow $DownloadISO 0
FunctionEnd

Function onUserAbort
	${If} $VENTOY_ACTIVE != 1
		;MessageBox MB_OK "Exiting the Program" ; Normal Process
	${Else}
		;MessageBox MB_OK "Returning to Drive and ISO Options"
		StrCpy $VENTOY_ACTIVE 0
		Call HideVentoyUI
		Call ShowSelectionsUI
		;Call UpdateCasperUI
		;Call RefreshUI
		Abort
	${EndIf}
	${If} $Removal != "YES"
		;MessageBox MB_OK "Exiting the Program" ; Normal Process
	${Else}
		${NSD_Uncheck} $Uninstaller
		Call Uninstall
		Abort
	${EndIf}
FunctionEnd