Option Explicit

Const UMDESKTOP_EXE = "%ProgramFiles%\UltraMon\UltraMonDesktop.exe"

Dim sh, fso
Set sh = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")

'check if UltraMon 3 or later is installed
Dim umVer
umVer = sh.RegRead("HKLM\Software\Realtime Soft\UltraMon\CurrentVersion")

'get the location of the wallpaper folder(s)
Dim dirWps(1)
If umVer = "" Then
	'UltraMon 2, location of the user and shared wallpaper folders stored in the registry
	dirWps(0) = sh.RegRead("HKCU\Software\Realtime Soft\UltraMon\Wallpaper\Wallpaper Directory")
	dirWps(1) = sh.RegRead("HKLM\Software\Realtime Soft\UltraMon\Wallpaper\All Users Wallpaper Directory")
Else
	'UltraMon 3 or later, wallpaper folder is at a known location
	dirWps(0) = sh.ExpandEnvironmentStrings("%APPDATA%\Realtime Soft\UltraMon\" & umVer & "\Wallpapers")
End If

Dim i
For i = 0 To UBound(dirWps)
	If dirWps(i) <> "" Then
		If Right(dirWps(i), 1) <> "\" Then dirWps(i) = dirWps(i) & "\"
	End If
Next

'get name of current wallpaper
Dim curWp
If umVer = "" Then
	'UltraMon 2, get current wallpaper bitmap
	curWp = sh.RegRead("HKCU\Control Panel\Desktop\Wallpaper")
	i = InStrRev(curWp, ".")
	curWp = Left(curWp, i) & "wallpaper"
Else
	'UltraMon 3 or later, get current UltraMon wallpaper
	curWp = sh.RegRead("HKCU\Software\Realtime Soft\UltraMon\" & umVer & "\Wallpaper\CurrentWallpaper")
	curWp = dirWps(0) & curWp & ".wallpaper"
End If

'enumerate available wallpapers
Dim fldWp, fileWp, nextOne, nextWp, firstWp, fileWpFullName
For i = 0 To UBound(dirWps)
	If dirWps(i) <> "" Then
		Set fldWp = fso.GetFolder(dirWps(i))
		For Each fileWp In fldWp.Files
			If Right(fileWp.Name, 10) = ".wallpaper" Then
				fileWpFullName = dirWps(i) & fileWp.Name
				
				If firstWp = "" Then firstWp = fileWpFullName
				
				If nextOne = True Then
					nextWp = fileWpFullName
					Exit For
				ElseIf fileWpFullName = curWp Then
					nextOne = True
				End If
			End If
		Next
		
		If nextWp <> "" Then Exit For
	End If
Next

If nextWp = "" Then nextWp = firstWp

'load next wallpaper
If nextWp <> "" And nextWp <> curWp Then
	Dim cmd : cmd = """" & UMDESKTOP_EXE & """ /load " & nextWp
	sh.Run cmd
Else
	Dim msg
	If nextWp = "" Then
		msg = "No wallpapers found in "
	Else
		msg = "Only a single wallpaper found in "
	End If
	msg = msg & dirWps(0)
	If dirWps(1) <> "" Then msg = msg & " and " & dirWps(1)
	msg = msg & ". UltraMon version is " & umVer & "."
	MsgBox msg,, WScript.ScriptName
End If
