; WPDOSAnyPrinterMethod.au3 - compiled script includes 14 files as noted below
; For the compiled script, see http://wpdos.org/automatedanyprinter.html  

#RequireAdmin
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Icon=wpicon-vista.ico
#AutoIt3Wrapper_Outfile=d:\AutoItScripts\WPDOSAnyPrinterMethod.exe
#AutoIt3Wrapper_Compression=4
#AutoIt3Wrapper_Res_Comment=WPDOS.org AnyPrinter Method Automated Installer
#AutoIt3Wrapper_Res_Description=WPDOS AnyPrinter Method Automated Installer
#AutoIt3Wrapper_Res_Fileversion=1.0.0.8
#AutoIt3Wrapper_Res_FileVersion_AutoIncrement=y
#AutoIt3Wrapper_Res_LegalCopyright=Edward Mendelson
#AutoIt3Wrapper_Res_SaveSource=y
#AutoIt3Wrapper_Res_Language=1033
#AutoIt3Wrapper_Au3Check_Stop_OnWarning=y
#AutoIt3Wrapper_Run_Tidy=y
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****

; This script requires full Administrative rights
; Installs sDirMon anyprinter method and drivers
; by Edward Mendelson em36-at-columbia-dot-edu
; 31 June 2006 for wpdos.org; revised 31 August 2010
; REQUIRES AutoIt3 3.3.4.0 or higher for Internet functions
; FileInstall routines require presence of 14 files:
;    The following are available on line from MSDN etc.:

;      DirMonitor.exe, sc.exe, ntrights.exe,
;      showset.exe, macascii.exe, wp.mrs
;    The following are available from WPDOS.org:

;      wp51gscr.all, wp60gscr.all
;    The following were written for this script:
;      autoexec.notame, inst5mac.txt, instgs6.txt,
;      wpdostmp.wpm, wpdos.ps, psprint.txt


$g_szVersion = "WPDOS.org"
If WinExists($g_szVersion) Then Exit ; It's already running
AutoItWinSetTitle($g_szVersion)
#include <_NTServices.au3>
#include <GUIConstants.au3>
#include <Process.au3>
#include <File.au3>
#include <ProgressConstants.au3>
AutoItSetOption("MustDeclareVars", 1)
AutoItSetOption("WinTitleMatchMode", 1)

Global Const $versionnumber = "2"
Dim $retver
Dim $msg, $ans, $ck
Dim $a, $e, $f, $g, $i, $q, $r, $u, $v, $y, $z
Dim $netprint, $ExtCmd, $RetCode, $ibtext
Dim $objWMIService, $colInstalledPrinters, $objPrinter, $uResult
Dim $gs1, $gs1num, $gs2, $gs2num, $gspath, $gskey, $gstype, $dmpath, $bLoop, $dLoop, $ploop, $sLoop
Dim $dm1, $nte, $pw2, $sce, $line1
Dim $newvar, $newcomma, $newname, $netprint, $tame
Dim $ptrvar, $result, $syscomma, $sysname, $sysvar, $sz
Dim $s_installed, $handle, $handle0, $handle1, $handle2, $handle3, $handle4, $handle5
Dim $objItem, $objWMIService, $colItems, $strComputer, $sysvar, $sz, $s_ServiceName
Dim $dtest, $gstxt, $gsok, $leftloc, $loclen, $rtloc, $trimrt
Dim $gsver2, $gsver, $gssubver, $gsmainver, $gsstring, $stringfound, $gsurl
Dim $gsline, $stringfound, $gswinclosed, $gsclosemsg
Dim $FileSize, $Pct, $BytesReceived
Dim $leftloc, $loclen, $rtloc, $trimrt, $gsver2, $gssubver, $gsmainver
Dim $label, $suggest, $gsdownfixed, $dllabel
Dim $a, $dmtmppath, $dmpthlen, $dmtmpbkslash, $dmstring, $wp5path, $dc, $pfpath, $pfline, $handle5, $handle6
Dim $stringfound, $wp5dir, $wp5read, $wp6dir, $wp6path, $wp6read, $nowp5, $msgnum, $setfile
Dim $WS_DLGFRAME, $SS_Center, $WS_EX_TOPMOST
Dim $btn_cancel, $nMsg, $ConfirmCancel, $CancelPressed, $pbar
Global $ptrname
Global $ptrcomma
Global $switchlabel, $dl_label, $slbl1, $slbl2
Global $pw = ""
Global $nopw = 0
Global $drv = @HomeDrive
Global $dmdir = @ProgramFilesDir & "\DirMonitor"
Global $dmtmpdir
Global Const $s = "sDirMon"
Global Const $t = "WPDOS AnyPrinter Method"
Global Const $gshtml = @TempDir & "\gsver.txt"
Global Const $gsinst = @TempDir & "\gsinst.exe"
Global Const $sctxt = @TempDir & "\scoutput.txt"
Global Const $nttxt = @TempDir & "\ntoutput.txt"
Global Const $wintemp = @WindowsDir & "\Temp"
Global $tameinst
Global $usedm = 0
Global $suggest
Global $err = 0
Global $status
Global $gsver
Global $gsstring
Global $enhanced = 0
;;change "yes" to "no" if Ghostscript cannot be downloaded automatically
Global $gsdownfixed = "yes"
If $gsdownfixed = "no" Then
    $gsver = "871"
    $gsstring = "8.71"
EndIf
Dim $downloadcomplete

;; Store this for future use
;Dim $s_String, $s_Start, $s_End
;Func _StringBetween($s_String, $s_Start, $s_End = 0)
;   $s_Start = StringInStr($s_String, $s_Start) + StringLen($s_Start)
;   Return StringMid($s_String, $s_Start, StringInStr($s_String, $s_End) - $s_Start)
;EndFunc   ;==>_StringBetween
;; end store for future use

;; Hourglass cursor for possible later use
;Func C1()
;   GUISetCursor(15, 1)
;EndFunc   ;==>C1
;; Ordinary cursor
;Func C0()
;   GUISetCursor()
;EndFunc   ;==>C0

;; Start actual program
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; NT-type only, not NT itself and Admin only
TestOSAdmin()

;; Opening message
OpenMsg()

;;Check if Tame installed
CheckTame()

;; Test if WP may be open
TestVDM()
;;do this twice if necessary
;; can also add a test via Tame:
;; <tamepath>\Tameview /pm wp.exe
;; if not errorlevel 1 goto allok

;; Determine printers and change if necessary
CheckPrinters()

;; Offer to print a test page
PrintTestPage()

;; Test Ghostscript version and file directory
GSData()
;; Note that this includes all the Ghostscript install functions

;; Setup Temporary Printfile Directory
SetTempDir()

;; Delete existing WPDOS.PS file if present
DelOldPSFile()

;; Test for sDirMon installed as service
TestSDirMon()

;; Install DirMonitor files and psprint.cmd
InstDirMonFiles()

;; Run DirMonitor -install to install service
InstServiceDirMon()

;; Change DirMonitor service to automatic startup
ConfigDirMonAuto()

;; Ask about enhanced installation
AskEnhanced()

;; Finally start the service
StartDirMonService()

;; Print test file?
PrintDMTest()

;; Start WPDos Installation
PtrDriverMsg()
;Exit

;; Test again for NTVDM
TestVDM()

;; Install for WP 51?
AskWP51()

;; Find WP51
FindWP51()

;; Ask WP51 folder if necessary
GetWP51Dir()

;; Copy All file
WP51AllFile()

;; Run WP with macro
WP51MacroRun()

;; Install for WP6?
AskWP6()

;; Find WP6
FindWP6()

;; Ask for WP6 folder if necessary
GetWP6Dir()

;; Copy ALL file
WP6AllFile()

;; Run WP6 with macro
WP6MacroRun()

;; Done!
InstComplete()

Exit

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

Func TestOSAdmin()
    If @OSType <> "WIN32_NT" Then
        MsgBox(270352, $t, "Not for use under Windows 95/98/Me or NT 4.0.")
        Exit
    EndIf
    If @OSVersion = "WIN_NT4" Then
        MsgBox(270352, $t, "Not for use under Windows 95/98/Me or NT 4.0.")
        Exit
    EndIf
    If IsAdmin() = 0 Then
        MsgBox(270352, $t, "You must be an administrator to run this program.")
        Exit
    EndIf
EndFunc   ;==>TestOSAdmin

Func OpenMsg()
    If @OSVersion = "WIN_VISTA" Then
        $a = MsgBox(270401, $t & " - Windows Vista Warning", _
                "Under Windows Vista, it is possible that this system" & @CRLF & _
                "may not work correctly. It works under some Vista" & @CRLF & _
                "systems but fails on others for obscure reasons." & @CRLF & @CRLF & _
                "If you prefer not to install a system that may or" & @CRLF & _
                "may not work on your sysem, choose Cancel." & @CRLF & @CRLF & _
                "User Access Control (UAC) must be active while" & @CRLF & _
                "installing. If UAC is turned off, choose Cancel.")
        If $a = 2 Then Cancelled()
    EndIf

    $a = MsgBox(270401, $t & " - Introduction (1 of 3)", _
            "This program installs a system for printing from" & @CRLF & _
            "WordPerfect for DOS to any Windows printer." & @CRLF & @CRLF & _
            "Install this system ONLY if no WordPerfect" & @CRLF & _
            "printer driver exists for your Windows printer." _
            & @CRLF & @CRLF & _
            "This sysytem is useful ONLY with so-called" & @CRLF & _
            "Windows-only printers, which do not use older" & @CRLF & _
            "printer languages such as PCL or PostScript," & @CRLF & _
            "for which WordPerfect was originally designed." & @CRLF & @CRLF & _
            "Warning: This system is slower than printing" & @CRLF & _
            "from WPDOS to a PCL or PostScript printer." _
            & @CRLF & @CRLF & _
            "This system will ONLY work if your printer is" & @CRLF & _
            "correctly installed and you can print from" & @CRLF & _
            "Windows programs such as your web browser." & @CRLF & @CRLF & _
            "If such programs cannot print, you MUST click" & @CRLF & _
            "Cancel now. Then install and test your Windows" & @CRLF & _
            "printer, and run this installation program again.")
    If $a = 2 Then Cancelled()

    $a = MsgBox(270401, $t & " - Introduction (2 of 3)", _
            "When installed, this system works as follows." & @CRLF & @CRLF & _
            "When WP prints a document, it will create the" & @CRLF & _
            "codes that it would send to a real PostScript" & @CRLF & _
            "printer if you had such a printer installed." & @CRLF & @CRLF & _
            "However, instead of sending codes directly to" & @CRLF & _
            "a printer, WP will instead write the codes to a" & @CRLF & _
            "file in a special folder on your disk." & @CRLF & @CRLF & _
            "A Directory Monitor program will be watching" & @CRLF & _
            "this special folder; when a new file is written" & @CRLF & _
            "to the folder, the Monitor will send the file to" & @CRLF & _
            "a program called Ghostscript." & @CRLF & @CRLF & _
            "Ghostscript will translate the PostScript codes" & @CRLF & _
            "in the file into codes that can be used by any" & @CRLF & _
            "Windows printer, and will send those codes to" & @CRLF & _
            "your Windows printer, which will print the file." & @CRLF & @CRLF & _
            "This program downloads and installs Ghostscript" & @CRLF & _
            "if it is not already installed on your system." & @CRLF & @CRLF & _
            "It also installs the Directory Monitor program" & @CRLF & _
            "and suitable WordPerfect printer drivers." & @CRLF & @CRLF & _
            "Finally, it runs WordPerfect and configures" & @CRLF & _
            "a printer driver for use with this system.")
    If $a = 2 Then Cancelled()

    $a = MsgBox(270401, $t & " - Introduction (3 of 3)", "You may choose between the Basic or Enhanced" & @CRLF & _
            "installation of this system. After setting up the" & @CRLF & _
            "Basic system, the installer will offer to set up the" & @CRLF & _
            "the Enhanced system so you can use it instead." & @CRLF & @CRLF & _
            "With the Basic system, you must run this installer" & @CRLF & _
            "again if you change your default Windows printer." _
            & @CRLF & @CRLF & _
            "The Enhanced system will automatically print to" & @CRLF & _
            "your current default printer, whatever the" & @CRLF & _
            "default printer may be at the time you print." & @CRLF & @CRLF & _
            "A Windows password is required for setting up" & @CRLF & _
            "the Enhanced system.")
    If $a = 2 Then Cancelled()
EndFunc   ;==>OpenMsg

Func CheckTame()
    $tame = RegRead("HKLM\Software\TameDOS", "TamePath")
    If $tame = "" Then
        $tame = RegRead("HKLM\Software\TameDOS", "TameFolder")
        If $tame = "" Then
            $a = MsgBox(270401, $t & " - TameDOS not installed", "The TameDOS utility was not found" & @CRLF & _
                    "on your system. WordPerfect will run very slowly" & @CRLF & _
                    "on your system if TameDOS is not installed." _
                    & @CRLF & @CRLF & _
                    "Please cancel this installation; visit" & @CRLF & _
                    "http://www.tamedos.com where you can download" & @CRLF & _
                    "TameDOS. Install TameDOS, then run this" & @CRLF & _
                    "installation program again.")
            If $a = 2 Then Cancelled()
        Else
            $tameinst = 1
        EndIf
    EndIf
EndFunc   ;==>CheckTame

Func CheckPrinters()
    $ptrvar = RegRead("HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows", "Device")
    $sysvar = RegRead("HKEY_USERS\.DEFAULT\Software\Microsoft\Windows NT\CurrentVersion\Windows", "Device")
    $netprint = StringInStr($ptrvar, "\")
    If $netprint = 1 Then
        MsgBox(270384, $t & " - Enhanced system required", "Your default printer seems to be a shared" & @CRLF & _
                "network printer. The Enhanced system will be required" & @CRLF & _
                "for use with a shared network printer.")
    EndIf
    ; following gets $ptrname for Enhanced system installation and MatchPrinters()
    $ptrcomma = StringInStr($ptrvar, ",")
    $ptrname = StringLeft($ptrvar, $ptrcomma - 1)
    If $sysvar <> $ptrvar Then MatchPrinters()
    ; If $sysvar == $ptrvar Then MsgBox(270336, $t, "Internal default printer and user default printer are already the same.")
EndFunc   ;==>CheckPrinters

Func PrintTestPage()
    If @OSVersion <> "WIN_VISTA" Then
        $a = MsgBox(270627, $t & " - Print printer test file?", "Test your default printer by printing a test file?" & @CRLF & @CRLF & _
                "If you recently installed a printer, choose Yes.")
        If $a = 2 Then Ended()
        If $a = 6 Then
            $objWMIService = ObjGet("winmgmts:{impersonationLevel=impersonate,(LoadDriver)}!\\" & @ComputerName & "\root\cimv2")
            $colInstalledPrinters = $objWMIService.ExecQuery("Select * from Win32_Printer Where Default = True")
            For $objPrinter In $colInstalledPrinters
                $uResult = $objPrinter.PrintTestPage()
            Next
            $a = MsgBox(270401, $t, "Please wait; if printing fails, choose Cancel, then install your printer in Windows.")
            If $a = 2 Then Cancelled()
        EndIf
    EndIf
    If @OSVersion = "WIN_VISTA" Then
        $a = MsgBox(270401, $t, _
                "If you have not recently printed to your default" & @CRLF & _
                "Windows printer, you should test it by printing" & @CRLF & _
                "a page from any standard Windows application." & @CRLF & @CRLF & _
                "This system will work ONLY if you can already" & @CRLF & _
                "print to your default Windows printer from a" & @CRLF & _
                "Windows application such as a web browser.")
        If $a = 2 Then Cancelled()
    EndIf
EndFunc   ;==>PrintTestPage

Func GSData()
    $gstype = "GPL"
    $gskey = "HKLM\Software\" & $gstype & " Ghostscript"
    $gs1 = RegEnumKey($gskey, 1)
    If @error Then
        ;If $gs1 = "" Then
        $gstype = "AFPL"
        $gskey = "HKLM\Software\" & $gstype & " Ghostscript"
        $gs1 = RegEnumKey($gskey, 1)
        If @error Then
            ;If $gs1 = "" Then
            $a = MsgBox(270387, $t & " - Ghostscript not found", "Ghostscript not found. Would you like me to download and install it?.")
            If $a = 2 Then Cancelled()
            If $a = 6 Then GetCurGSVer()
            If $a = 7 Then
                MsgBox(270336, $t, "Install Ghostscript manually and restart this program.")
                Cancelled()
            EndIf
        EndIf
    EndIf
    Global $i = 2
    $gs1num = Number($gs1)
    While 1
        $gs2 = RegEnumKey($gskey, $i)
        If @error Then ExitLoop
        ;If $gs2 = "" Then ExitLoop
        $gs2num = Number($gs2)
        If $gs2num > $gs1num Then $gs1 = $gs2
        $i = $i + 1
    WEnd
    If $downloadcomplete <> 1 Then
        $a = MsgBox(270401, $t, "Your current Ghostscript seems to be " & $gstype & " Ghostscript " & $gs1 & "." & @CRLF & @CRLF & _
                "If you are certain that you have installed a later version," & @CRLF & _
                "Cancel now, and uninstall all versions that you no longer use.")
    EndIf
    If $a = 2 Then Cancelled()

    $gspath = RegRead($gskey & "\" & $gs1, "GS_DLL")
    $gspath = StringTrimRight($gspath, 11)
    $gspath = $gspath & "gswin32c.exe"

    If Not FileExists($gspath) Then
        MsgBox(270352, $t, "Can't find Ghostscript program file. Reinstall Ghostscript.")
        Exit
    EndIf
    ;   $a = MsgBox(270337, $t, "This system will use Ghostscript file: " & $gspath)
    ;   If $a = 2 Then Cancelled()
EndFunc   ;==>GSData

Func SetTempDir()
    $dmtmppath = RegRead("HKLM\SOFTWARE\WPDOS.org", "PrintFilePath")
    ;MsgBox(0,"", $dmtmppath)
    If $dmtmppath <> "" Then
        ;MsgBox(0, "", "$dmtmppatth is " & $dmtmppath)
        $dmtmpbkslash = StringInStr($dmtmppath, "\", 0, -1)
        ;MsgBox(0, "", "Bkslash pos is " & $dmtmpbkslash)
        $suggest = StringTrimLeft($dmtmppath, $dmtmpbkslash)
        ;MsgBox(0, "", "$suggest is " & $suggest)
        If _ServiceExists($s) Then
            $handle1 = FileOpen($dmdir & "\dirmonitor.ini", 0)
            $q = FileReadLine($handle1, 2)
            $dmpthlen = StringLen($dmtmppath)
            $q = StringLeft($q, $dmpthlen)
            ;;;;
            $retver = RegRead("HKLM\Software\WPDOS.org", "VersionNumber")
            ;MsgBox(0,'', $retver)
            If $retver < $versionnumber Then
                $usedm = 0
                Return
            EndIf
            If $downloadcomplete = 1 Then; force reinstall of DirMon if Ghostscript downloaded
                $usedm = 0
                Return
            EndIf
            ;;;;
            If $dmtmppath = $q Then
                $a = MsgBox(270387, $t & " - Use existing setup?", _
                        "Use your existing Directory Monitor setup, with" & @CRLF & _
                        "the directory used for temporary print files set" & @CRLF & _
                        "as: " & $dmtmppath & " ?" & @CRLF & @CRLF & _
                        "Choose No if you wish to remove, change, or" & @CRLF & _
                        "repair an existing setup, or if you changed your" & @CRLF & _
                        "default printer and this system no longer prints.")
                If $a = 2 Then Cancelled()
                If $a = 6 Then
                    $usedm = 1
                    Return
                EndIf
            EndIf
            ; Exit
        EndIf
    Else
        $suggest = "tempwp"
        $dmtmppath = $drv & "\" & $suggest
    EndIf
    ;;next needed???
    If $usedm = 1 Then Return
    ;; next needed???
    $dLoop = 1
    $dmtmpdir = ""
    While $dLoop = 1
        ;; use Func to put InputBox on top
        $ans = _InputBoxOnTop($t, "Folder for temporary printfiles in root directory of drive " & $drv, $suggest, "", -1, 140)
        If $err Then Cancelled()
        $dmtmpdir = $ans
        If StringLeft($dmtmpdir, 1) = "\" Then $dmtmpdir = StringTrimLeft($dmtmpdir, 1)
        If $dmtmpdir = "" Then
            $a = MsgBox(270385, "Error", "You must enter a directory name.")
            If $a = 2 Then Cancelled()
        ElseIf $dmtmpdir = "\" Then
            $a = MsgBox(270385, "Error", "You must enter a directory name.")
            If $a = 2 Then Cancelled()
        ElseIf StringIsAlNum($dmtmpdir) = 0 Then
            $a = MsgBox(270385, "Error", "Alphanumeric characters only. Please try again.")
            If $a = 2 Then Cancelled()
        ElseIf StringLen($dmtmpdir) > 8 Then
            $a = MsgBox(270385, "Error", "Maximum 8 characters. Please try again.")
            If $a = 2 Then Cancelled()
        Else
            ExitLoop
        EndIf
    WEnd

;~  $dtest = StringSplit("nul,CON,LPT1,COM1", ",")
;~  For $x = 1 To $dtest[0]
;~      If StringInStr($dmtmpdir, $dtest[$x]) Then
;~          $a = MsgBox(270385, "Error", $dtest[$x] & " is not allowed. Please try again.")
;~          If $a = 2 Then Cancelled()
;~      Else
;~          ExitLoop
;~          SetTempDir()
;~      EndIf
;~  Next
;~
    $dmtmppath = $drv & "\" & $dmtmpdir
    If FileExists($dmtmppath) = 0 Then
        $a = MsgBox(270369, $t, "Create " & $dmtmppath & " directory?")
        If $a = 2 Then Cancelled()
        $e = DirCreate($dmtmppath)
        If $e = 0 Then
            MsgBox(270353, $t, "Error creating directory.")
            Exit
        EndIf
    Else
        $a = MsgBox(270369, $t, "Use existing " & $dmtmppath & " directory?")
        If $a = 2 Then Cancelled()
    EndIf
    ;; Record printfile spool path in registry
    RegWrite("HKLM\Software\WPDOS.org", "PrintFilePath", "REG_SZ", $dmtmppath)
    MsgBox(270400, $t, "WPDOS printfile will be set to " & $dmtmppath & "\wpdos.ps in WP printer driver.")
EndFunc   ;==>SetTempDir

Func DelOldPSFile()
    If FileExists($dmtmppath & "\wpdos.ps") Then
        FileDelete($dmtmppath & "\wpdos.ps")
        MsgBox(270400, $t, "An existing temporary print file was found and deleted.")
    EndIf
EndFunc   ;==>DelOldPSFile

Func TestSDirMon()
    If $usedm = 1 Then Return
    If _ServiceExists($s) Then
        $s_installed = 1
        $a = MsgBox(270401, $t, "Director Monitor service is currently installed." & @LF & @LF & _
                "It will be uninstalled, then optionally reinstalled.")
        If $a = 2 Then Cancelled()
        UninstDirMon()
    Else
        MsgBox(270384, $t, "Directory Monitor service will be installed.")
    EndIf
EndFunc   ;==>TestSDirMon

Func UninstDirMon()
    If $usedm = 1 Then Return
    ;;;;BlockInput(1)
    $slbl1 = "Please wait during uninstallation..."
    GUICreate($t, 240, 85, -1, -1, $WS_DLGFRAME)
    $dl_label = GUICtrlCreateLabel($slbl1, 40, 20, 160, 20, $SS_Center)
    GUISetState(@SW_SHOW)
    $dm1 = RegRead("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\sDirMon", "ImagePath")
    ServiceStatus()
    If $status = "Running" Then
        $sLoop = 1
        While $sLoop = 1
            _ServiceStop($s)
            Sleep(200)
            $status = _ServiceStatus($s)
            If $status = 0 Then
                ExitLoop
            EndIf
        WEnd
    EndIf
    $dmdir = StringTrimRight($dm1, 15)
    Run(@ComSpec & " /c " & 'dirmonitor.exe -uninstall', $dmdir, @SW_HIDE)
    $z = WinWait("Directory Monitor Service", "", 40)
    GUIDelete()
    ;;;BlockInput(0)
    If WinExists("Directory Monitor Service", "unable") Then
        MsgBox(270352, $t, "Problem uninstalling Directory Monitor; please run this program again.")
        Exit
    EndIf
    If Not WinExists("Directory Monitor Service", "uninstalled") Then
        MsgBox(270352, $t, "Problem uninstalling Directory Monitor; please run this program again.")
    EndIf
    If $z = 0 Then
        ;; guidelete was here
        MsgBox(270352, $t, "Problem uninstalling Directory Monitor; please run this program again.")
        Exit
    Else
        ControlSend("Directory Monitor Service", "uninstalled", "Button1", "{Enter}")
        GUIDelete()
        $a = MsgBox(270385, $t, "Directory Monitor uninstalled. To exit without reinstalling, choose Cancel.")
        If $a = 2 Then DMEnded()
    EndIf
EndFunc   ;==>UninstDirMon

Func MatchPrinters()
    $a = MsgBox(270337, $t, _
            "Your default printer will now be specified" & @CRLF & _
            "as Windows's internal default printer." & @CRLF & @CRLF & _
            "This will have no effect on the way you print" & @CRLF & _
            "or on your choice of printers. It merely" & @CRLF & _
            "allows this method to work smoothly.")
    If $a = 2 Then Cancelled()
    ;; next two lines moved above
    ;; $ptrcomma = StringInStr($ptrvar, ",")
    ;; $ptrname = StringLeft($ptrvar, $ptrcomma - 1)
    $a = MsgBox(270401, $t, "Your current user default printer: " & $ptrname)
    If $a = 2 Then Cancelled()

    $syscomma = StringInStr($sysvar, ",")
    $sysname = StringLeft($sysvar, $syscomma - 1)
    $a = MsgBox(270401, $t, "Current system default printer (will be changed to user default): " & $sysname)
    If $a = 2 Then Cancelled()

    $result = RegWrite("HKEY_USERS\.DEFAULT\Software\Microsoft\Windows NT\CurrentVersion\Windows", "Device", "REG_SZ", $ptrvar)
    If $result = 0 Then
        MsgBox(270352, $t, "The script was unable to write to the registry; no changes made.")
        Exit
    EndIf
    $newvar = RegRead("HKEY_USERS\.DEFAULT\Software\Microsoft\Windows NT\CurrentVersion\Windows", "Device")
    $newcomma = StringInStr($newvar, ",")
    $newname = StringLeft($newvar, $newcomma - 1)
    MsgBox(270400, $t, "Success! System and user default printers are now both: " & $newname)
EndFunc   ;==>MatchPrinters

Func ServiceStatus()
    $status = _ServiceStatus($s)
    ; MsgBox(270336, $t, $s & " status is " & $status)
EndFunc   ;==>ServiceStatus

Func StopService()
    _ServiceStop($s)
    $status = _ServiceStatus($s)
    ; MsgBox(270336, $t, $s & " status is " & $status & " - SHOULD BE STOPPED.")
EndFunc   ;==>StopService

Func InstDirMonFiles()
    If $usedm = 1 Then Return
    If FileExists($dmdir) Then
        $dmpath = $dmdir & "\"
        If FileExists($dmpath & "DirMonitor.exe") Then
            ; MsgBox(270336, $t, "Found " & $dmpath & "DirMonitor.exe")
            $sz = FileGetSize($dmpath & "DirMonitor.exe")
            If $sz <> 54784 Then
                MsgBox(270352, $t, "Different Directory Monitor Program installed. Cannot proceed.")
                Exit
            EndIf
            ; MsgBox(270336, $t, "DirMonitor.Exe already exists.")
        Else
            ; MsgBox(270336, $t, "DirMonitor.Exe does NOT exist.")
        EndIf
    Else
        DirCreate($dmdir)
        $dmpath = $dmdir & "\"
        Sleep(10)
    EndIf
    FileInstall("v:\DirMonFiles\DirMonitor.exe", $dmpath & "DirMonitor.exe", 1)
    FileInstall("v:\DirMonFiles\psprint.txt", $dmpath & "psprint.txt", 1)
    $handle0 = FileOpen($dmpath & "Dirmonitor.ini", 2)
    FileWriteLine($handle0, "[directories]")
    FileWriteLine($handle0, $dmtmppath & "=" & Chr(34) & $dmpath & "psprint.cmd" & Chr(34))
    FileClose($handle0)
    _FileWriteToLine($dmpath & "psprint.txt", 1, "set gspath=" & Chr(34) & $gspath & Chr(34), 0)
    _FileWriteToLine($dmpath & "psprint.txt", 2, "set dmtmpdrv=" & $drv, 0)
    _FileWriteToLine($dmpath & "psprint.txt", 3, "set dmtmpdir=\" & $dmtmpdir, 0)
    ;   _FileWriteToLine($dmpath & "psprint.txt", 4, "set praw=" & Chr(34) & $dmdir & "\printraw.exe" & Chr(34), 0)
    FileMove($dmpath & "psprint.txt", $dmpath & "psprint.cmd", 1)
    $handle2 = FileOpen($dmpath & "psprint.cmd", 0)
    $line1 = FileReadLine($dmpath & "psprint.cmd", 1)
    FileClose($handle2)
    If $line1 <> "set gspath=" & Chr(34) & $gspath & Chr(34) Then
        MsgBox(270352, $t, "Error writing PsPrint.cmd file.")
        Exit
    EndIf
    FileDelete($dmpath & "psprint.txt")
    Sleep(10)
EndFunc   ;==>InstDirMonFiles

Func InstServiceDirMon()
    If $usedm = 1 Then Return
    ; BlockInput(1)
    $slbl1 = "Please wait during installation..."
    GUICreate($t, 240, 85, -1, -1, $WS_DLGFRAME)
    $dl_label = GUICtrlCreateLabel($slbl1, 40, 20, 160, 20, $SS_Center)
    GUISetState(@SW_SHOW)
    Run(@ComSpec & " /c " & 'dirmonitor.exe -install', $dmdir, @SW_HIDE)
    $z = WinWait("Directory Monitor Service", "", 40)
    GUIDelete()
    BlockInput(0)
    If WinExists("Directory Monitor Service", "unable") Then
        MsgBox(270352, $t, "Problem installing Directory Monitor; please run this program again.")
        Exit
    EndIf
    If Not WinExists("Directory Monitor Service", "has been installed") Then
        MsgBox(270352, $t, "Problem uninstalling Directory Monitor; please run this program again.")
    EndIf
    If $z = 0 Then
        GUIDelete()
        MsgBox(270352, $t, "Problem installing Directory Monitor; please run this program again.")
        Exit
    Else
        ControlSend("Directory Monitor Service", "has been installed", "Button1", "{Enter}")
        GUIDelete()
    EndIf
EndFunc   ;==>InstServiceDirMon

Func ConfigDirMonAuto()
    If $usedm = 1 Then Return
    $sce = FileExists(@SystemDir & "\sc.exe")
    If $sce = 0 Then FileInstall("f:\winutil\ResourceKit\sc.exe", @SystemDir & "\sc.exe", 0)
    RunWait(@ComSpec & " /c " & 'sc.exe config sDirMon start= auto', "", @SW_HIDE)
EndFunc   ;==>ConfigDirMonAuto

Func StartDirMonService()
    If $usedm = 1 Then Return
    _ServiceStart($s)
    Sleep(500)
    ServiceStatus()
    ;MsgBox(270400, $t, "Directory Monitor installed and running.")
EndFunc   ;==>StartDirMonService

Func AskEnhanced()
    $nopw = 0
    If $usedm = 1 Then Return
    RegWrite("HKLM\Software\WPDOS.org", "VersionNumber", "REG_DWORD", $versionnumber)
    ;If @OSVersion = "WIN_Vista" Then
    ;   MsgBox(270352, $t, "Windows Vista REQUIRES you to install the Enhanced configuration from the next dialog box.")
    ;EndIf
    $a = MsgBox(270627, $t & " - Install Enhanced system?", "Director Monitor basic system installed." & @CRLF & _
            "Do you want to install the Enhanced system?" & @CRLF & @CRLF & _
            "The basic system (already installed) will print to" & @CRLF & _
            "your current default Windows printer:" & @CRLF & _
            $ptrname & @CRLF & @CRLF & _
            "You should install the Enhanced system if you" & @CRLF & _
            "frequently change your default Windows printer." & @CRLF & _
            "The Enhanced system automatically prints to" & @CRLF & _
            "whichever printer is your current default." & @CRLF & @CRLF & _
            "A Windows password is required for setting up" & @CRLF & _
            "the Enhanced system." & @CRLF & @CRLF & _
            "If you do not install the Enhanced system, you must" & @CRLF & _
            "run this program again if you change your default" & @CRLF & _
            "Windows printer." & @CRLF & @CRLF & _
            "Choose Yes to install the Enhanced system; or No" & @CRLF & _
            "to continue with the Basic system (already installed).")
    If $a = 2 Then Cancelled()
    If $a = 6 Then
        ; MsgBox(270336, $t, "You said Yes. Enhanced installation will begin.")
        InstallEnhanced()
        If $nopw = 1 Then AskEnhanced()
        ;Exit
        ; ElseIf $a = 7 Then MsgBox(270336, $t, "You said No; will start service.")
    EndIf
EndFunc   ;==>AskEnhanced

Func InstallEnhanced()
    $enhanced = 0
    $nopw = 0
    $u = @ComputerName & "\" & @UserName
    ;; MsgBox(270336, $t, "User name is " & $u)
    Password()
    If $nopw = 1 Then Return
    ;MsgBox(270336, $t, "Your password is: " & $pw)
    $nte = 0
    $nte = FileExists(@TempDir & "\ntrights.exe")
    $slbl1 = "Please wait while permissions are configured..."
    GUICreate($t, 300, 85, -1, -1, $WS_DLGFRAME)
    $dl_label = GUICtrlCreateLabel($slbl1, 40, 20, 220, 20, $SS_Center)
    GUISetState(@SW_SHOW)
    If $nte = 0 Then FileInstall("f:\winutil\ResourceKit\ntrights.exe", @TempDir & "\ntrights.exe", 0)
    ;;;  Loop here runs ntrights.exe three times to get it to work
    $g = 1
    For $g = 1 To 3
        RunWait(@ComSpec & " /c " & @TempDir & '\ntrights.exe -u ' & $u & ' +r SeServiceLogonRight ' & " >" & $nttxt, "", @SW_HIDE)
        Sleep(100)
        $handle3 = FileOpen($nttxt, 0)
        $line1 = FileReadLine($handle3, 1)
        FileClose($handle3)
        FileDelete($nttxt)
        ;Sleep(10)
        If StringInStr($line1, "successful") Then
            $y = "RightsOK"
            ;MsgBox(0,"", $y)
            ExitLoop
        EndIf
        ;$g = $g + 1
        Sleep(100)
    Next
    If $nte = 0 Then
        FileDelete(@TempDir & "\ntrights.exe")
        Sleep(10)
    EndIf
    If $y <> "RightsOK" Then
        MsgBox(270352, $t, "Problem setting service logon rights. Please run this program again.")
        Exit
    EndIf
    ; MsgBox(270400, $t, "Services logon permissions correctly set for current user.")
    ;; set user logon rights
    ;; test if win/sys32/sc.exe exists; if not FileInstall it in @TempDir then remove
    $sce = FileExists(@SystemDir & "\sc.exe")
    If $sce = 0 Then FileInstall("f:\winutil\ResourceKit\sc.exe", @SystemDir & "\sc.exe", 0)
    RunWait(@ComSpec & " /c " & @SystemDir & '\sc.exe config sDirMon obj= ' & $u & ' password= ' & $pw & " >" & $sctxt, "", @SW_HIDE)
    $pw = 0
    $handle4 = FileOpen($sctxt, 0)
    $line1 = ""
    $line1 = FileReadLine($handle4, 1)
    FileClose($handle4)
    FileDelete($sctxt)
    Sleep(10)
    GUIDelete()
    If Not StringInStr($line1, "SUCCESS") Then
        MsgBox(270352, $t, "Problem setting Directory Monitor logon. Please run this installer again.")
        Exit
        ; Else MsgBox(270336, $t, "Directory Monitor logon set to " & $u & ".")
    EndIf
    $enhanced = 1
EndFunc   ;==>InstallEnhanced

Func Password()
    $nopw = 0
    $bLoop = 1
    While $bLoop = 1
        $pw = ""
        $ans = _InputBoxOnTop($t, "Enter your Windows password: ", "", "*", -1, 130)
        If $err Then Ended()
        $pw = $ans
        If $pw = "" Then
            MsgBox(270384, $t, "The Enhanced system can be used only with a Windows password.")
            $nopw = 1
            Return
            ;Cancelled()
        EndIf
        ;;  MsgBox(270336, $t, "You entered " & $pw)
        ;$pw2 = InputBox($t, "Re-enter password", "", "*", -1, 130)
        $ans = _InputBoxOnTop($t, "Re-enter password: ", "", "*", -1, 130)
        If $err Then Ended()
        $pw2 = $ans
        ;;  MsgBox(270336, $t, "You entered " & $pw2)
        If $pw = $pw2 Then
            $pw2 = 0
            ExitLoop
        Else
            $a = MsgBox(270385, $t, "Passwords do not match. Please try again.")
            If $a = 2 Then Cancelled()
        EndIf
    WEnd
    ;If Not RunAs(@UserName, '', $pw, 0) Then
    ;   MsgBox(270352, $t, 'This feature requires Windows 2000 or above).')
    ;   Exit
    ;EndIf
    ;;;$ExtCmd = @ComSpec & ' /c echo "Testing credentials for: "' & @UserName
    ;;;; Opt("RunErrorsFatal", 0); 0=Do not exit, set @Error on fail - Not needed in latest version
    ;;;$RetCode = RunWait($ExtCmd, @TempDir, @SW_HIDE)
    ;;; $pw = InputBox('RunAs Test', 'Enter your password: ', '', '*')
    ;;;; MsgBox(270336, $t, "Your password is: " & $pw)
    $RetCode = RunAs(@UserName, @ComputerName, $pw, 0, @ComSpec & " /c echo.", @TempDir, @SW_HIDE)
    If Not (@error = 0 And $RetCode <> 0) Then
        MsgBox(270352, $t, 'Incorrect Windows password entered for user ' & @UserName & '!')
        Password()
    EndIf
EndFunc   ;==>Password

Func PrintDMTest()
    If $usedm = 1 Then
        $dmstring = "already"
    Else
        If $enhanced = 1 Then
            $dmstring = "enhanced system"
        Else
            $dmstring = "basic system"
        EndIf
    EndIf
    ; add delete print file in Windows Temp directory if needed
    If FileExists($wintemp & "\wpdos.ps") Then
        FileDelete($wintemp & "\wpdos.ps")
        MsgBox(270400, $t, "An existing temporary print file was found and deleted.")
    EndIf
    ;MsgBox(0, $t, "path for file is " & $dmtmppath)
    $a = MsgBox(270627, $t & " - Print Directory Monitor test file?", "Directory Monitor " & $dmstring & " installed." & @CRLF & @CRLF & _
            "Print a test file?") ; formerly 270627
    If $a = 2 Then Ended()
    If $a = 6 Then
        FileInstall("v:\DirMonFiles\wpdos.ps", $dmtmppath & "\wpdos.ps", 1)
        $a = MsgBox(270401, $t, "Please wait; test file should begin printing soon. If printing fails, press Cancel, and run the installer again.")
        If $a = 2 Then Ended()
    EndIf
EndFunc   ;==>PrintDMTest

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Helper Routines follow

Func Cancelled()
    MsgBox(270352, $t, "Script cancelled; no changes made.")
    Exit
EndFunc   ;==>Cancelled

Func DMProblem()
    MsgBox(270352, $t, "Problem uninstalling Directory Monitor. Please run this program again.")
    Exit
EndFunc   ;==>DMProblem

Func DMProblemInst()
    MsgBox(270352, $t, "Problem installing Directory Monitor. Please run this program again.")
    Exit
EndFunc   ;==>DMProblemInst

Func Ended()
    MsgBox(270352, $t, "Script cancelled.")
    Exit
EndFunc   ;==>Ended

Func DMEnded()
    MsgBox(270352, $t, "Script cancelled. The folders " & $dmdir & " and " & $dmtmppath & " may be deleted.")
    Exit
EndFunc   ;==>DMEnded

Func _ServiceExists($s_ServiceName, $strComputer = "localhost")
    Const $wbemFlagReturnImmediately = 0x10
    Const $wbemFlagForwardOnly = 0x20
    Local $colItems = ""
    $objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\CIMV2")
    $colItems = $objWMIService.ExecQuery("SELECT * FROM Win32_Service where Name = '" & $s_ServiceName & "'", "WQL", _
            $wbemFlagReturnImmediately + $wbemFlagForwardOnly)
    If IsObj($colItems) Then
        For $objItem In $colItems
            Return 1
        Next
        Return 0
    EndIf
    SetError(1)
    Return 0 ;object not created
EndFunc   ;==>_ServiceExists

Func InstComplete()
    MsgBox(270400, $t, "Installation complete.")
EndFunc   ;==>InstComplete

;; End Helper Routines
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;; Ghostscript install routines

Func GetCurGSVer()
    If $gsdownfixed = "no" Then ParseGSVerString()
    If $downloadcomplete = 1 Then Return
    $slbl1 = "Checking for current Ghostscript version..."
    GUICreate($t, 280, 120, -1, -1, $WS_DLGFRAME)
    $dl_label = GUICtrlCreateLabel($slbl1, 40, 20, 220, 50, $SS_Center)
    $btn_cancel = GUICtrlCreateButton("Cancel", 90, 50, 80, 25)
    GUISetState(@SW_SHOW)
    ;;;;;;;;;
    $v = InetGet("http://ghostscript.com/releases/", $gshtml, 1, 1)
    ;;;$v = InetGet("http://mirror.cs.wisc.edu/pub/mirrors/ghost/GPL/current/", $gshtml, 1, 1)
    Do
        $nMsg = GUIGetMsg()
        If $nMsg = $btn_cancel Then
            $ConfirmCancel = MsgBox(4, "Cancel Version Check?", "Do you want to cancel the version check?", -1, $dllabel)
            ; Check if they said Yes to confirm cancel
            If $ConfirmCancel = 6 Then
                GUIDelete()
                InetClose($v)
                Cancelled()
            EndIf
        EndIf
    Until InetGetInfo($v, 2)
    ;;;;;;;;;
    GUIDelete()
    ;;;;;;;;;
    If $v = 0 Then
        MsgBox(270442, $t, "Error: Unable to check Ghostcript version. Install Ghostscript manually and rerun this program.")
        Exit
    EndIf
    $gstxt = FileOpen($gshtml, 0)
    If $gstxt <> -1 Then
        $stringfound = 0
        While 1
            $gsline = FileReadLine($gstxt)
            If @error Then ExitLoop
            If StringInStr($gsline, 'w32.exe') Then
                $stringfound = 1
                ExitLoop
            EndIf
        WEnd
        ;       MsgBox(270336, $t, $stringfound)
        If Not $stringfound Then
            MsgBox(270352, $t, "Could not read downloaded version data. Install Ghostscript manually, then rerun this program.")
            Exit
        EndIf
        FileClose($gstxt)
    Else
        MsgBox(270352, $t & ' FileOpen Error', "Could not download version information. Install Ghostscript manually, then rerun this program.")
        Exit
    EndIf
    FileDelete($gshtml)
    InetClose($v)
    Sleep(10)
    ;MsgBox(0, $t, $gsline)
    ParseGSVerString()
EndFunc   ;==>GetCurGSVer

Func ParseGSVerString()
    If $gsdownfixed = "no" Then DownInstGS()
    ;;used to be get not gs in next
    $leftloc = StringInStr($gsline, "gs") + 1
    $loclen = StringLen($gsline)
    $rtloc = StringInStr($gsline, "w32") - 1
    $trimrt = $loclen - $rtloc
    $gsver2 = StringTrimRight($gsline, $trimrt)
    $gsver = StringTrimLeft($gsver2, $leftloc)
    ;MsgBox(0, $t, $gsver)
    $gssubver = StringRight($gsver, 2)
    $gsmainver = StringTrimRight($gsver, 2)
    $gsstring = $gsmainver & "." & $gssubver
    ;MsgBox(0, $t, $gsstring)
    DownInstGS()
EndFunc   ;==>ParseGSVerString

Func DownInstGS()
    If $downloadcomplete = 1 Then Return
    $a = MsgBox(270401, $t, "Will try to download Ghostscript " & $gsstring & ". This may take a while.")
    If $a = 2 Then Cancelled()
    If FileExists($gsinst) Then
        FileDelete($gsinst)
        Sleep(10)
    EndIf

    $slbl1 = "Please wait during download..."
    GUICreate($t, 286, 142, -1, -1, $WS_DLGFRAME)
    ;;; was: GUICreate($t, 280, 85, -1, -1, $WS_DLGFRAME)
    $dl_label = GUICtrlCreateLabel($slbl1, 92, 18) ;; , 80, 20, $SS_Center
    $pbar = GUICtrlCreateProgress(38, 42, 200, 20, $PBS_SMOOTH)
    $btn_cancel = GUICtrlCreateButton("Cancel", 100, 78, 80, 25)
    GUISetState(@SW_SHOW)
    If $gsdownfixed = "no" Then
        $gsurl = "http://mirror.switch.ch/ftp/mirror/ghost/GPL/gs" & $gsver & "/gs" & $gsver & "w32.exe"
        $f = InetGet($gsurl, $gsinst, 1, 1)
        ;;$downloadcomplete = 1
    Else
        ;;; $gsurl = "http://mirror.cs.wisc.edu/pub/mirrors/ghost/GPL/current/gs" & $gsver & "w32.exe"
        $gsurl = "http://ghostscript.com/releases/gs" & $gsver & "w32.exe"
        $f = InetGet($gsurl, $gsinst, 1, 1)
        ;;$downloadcomplete = 1
    EndIf
    $FileSize = InetGetSize($gsurl) ;Get file size
    If $f = 0 Or $FileSize = 0 Then
        MsgBox(270352, $t, "Error: Unable to download Ghostcript " & $gsstring & ". The web site may be busy." _
                & @LF & @LF & "Wait a few moments and run this program again, or install Ghostscript manually before running this program.")
        Exit
    EndIf

    ;; $a = MsgBox(0, $t, $gsurl)
    ;; $a = MsgBox(0, $t, "File size: " & $FileSize)
    ;; While Not InetGetInfo($f, 2) ;Loop until download is finished
    GUICtrlSetData($dl_label, "File size: " & $FileSize)
    Do
        ;If InetGetInfo($f, 0) > 0 Then
        $nMsg = GUIGetMsg()
        If $nMsg = $btn_cancel Then
            $ConfirmCancel = MsgBox(4, "Cancel Download?", "Do you want to cancel the download?", -1, $dllabel)
            ; Check if they said Yes to confirm cancel
            If $ConfirmCancel = 6 Then
                GUIDelete()
                ; Abort the download
                InetClose($f)
                Cancelled()
            EndIf
        EndIf
        ;; While Not InetGetInfo($f, 2) ;Loop until download is finished
        $BytesReceived = InetGetInfo($f, 0) ;Get bytes received
        $Pct = Int($BytesReceived / $FileSize * 100) ;Calculate percentage
        ;; ProgressSet($Pct, $Pct & "%") ;Set progress bar
        ;; GUICtrlSetData($dl_label, $BytesReceived & " bytes downloaded, " & $Pct & "% done.")
        ; Update the  progress bar
        GUICtrlSetData($pbar, $Pct)
        ; EndIf
    Until InetGetInfo($f, 2)
    ;;;Sleep(500)
    ;;;WEnd

    GUIDelete()
    InetClose($f)
    ;; next moved down here
    $downloadcomplete = 1

    $a = MsgBox(270401, $t, "Download complete. Install Ghostscript " & $gsstring & "?" & @LF & @LF & "(Installation will be automatic.)")
    If $a = 2 Then Cancelled()
    GUICreate($t, 240, 85, -1, -1, $WS_DLGFRAME)
    $label = GUICtrlCreateLabel("Please wait; extracting installer...", 40, 20, 160, 20, $SS_Center, $WS_EX_TOPMOST)
    GUISetState(@SW_SHOW)
    Run($gsinst, @TempDir)
    WinWait("WinZip Self-Extractor - gsinst.exe")
    WinSetState("WinZip Self-Extractor - gsinst.exe", "", @SW_MINIMIZE)
    ControlSend("WinZip Self-Extractor - gsinst.exe", "", "Button1", "{Enter}")
    ;WinSetState("WinZip Self-Extractor - gsinst.exe", "", @SW_MINIMIZE)
    WinWait("GPL Ghostscript Setup")
    ControlSend("GPL Ghostscript Setup", "This installs", "Button1", "{Enter}")
    GUIDelete()
    ;WinWait("GPL Ghostscript setup log")
    ; BlockInput(1)
    GUICreate($t, 240, 85, -1, -1, $WS_DLGFRAME)
    $label = GUICtrlCreateLabel("Please wait during installation...", 40, 20, 160, 20, $SS_Center, $WS_EX_TOPMOST)
    GUISetState(@SW_SHOW)
    WinWait("GPL Ghostscript setup log")
    WinWaitClose("GPL Ghostscript setup log")
    WinWaitClose("GPL Ghostscript Setup")
    Sleep(20)
    ;;wait for Explorer window on GS shortcuts
    AutoItSetOption("WinTitleMatchMode", 2)
    $gswinclosed = 0
    If WinExists("Ghostscript") Then
        WinClose("Ghostscript")
        $gswinclosed = 1
    EndIf
    AutoItSetOption("WinTitleMatchMode", 1)
    Sleep(20)
    FileDelete($gsinst)
    GUIDelete()
    BlockInput(0)
    ;Sleep(200)
    $gs1 = RegEnumKey("HKLM\Software\GPL Ghostscript", 1)
    ;If $gs1 = "" Then
    If @error Then
        MsgBox(270352, $t, "Error installing Ghostcript. Please run this program again.")
        Exit
    EndIf
    If $gswinclosed = 0 Then $gsclosemsg = " You may close any open Ghostscript window."
    MsgBox(270336, $t, "Ghostscript installation complete. Press OK and wait a moment." & $gsclosemsg)
    GSData()
EndFunc   ;==>DownInstGS

;;;;;;; End Ghostscript install routines

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; WordPerfect setup routines

Func TestVDM()
    If ProcessExists("NTVDM.exe") Then
        $a = MsgBox(270385, $t, "If WordPerfect for DOS is running, close it before clicking OK.")
        If $a = 2 Then Exit
    EndIf
EndFunc   ;==>TestVDM

Func PtrDriverMsg()
    $a = MsgBox(270401, $t & " - Setup WPDOS printer drivers", _
            "This installation can set up printer drivers for" & @CRLF & _
            "WPDOS 5.1 or 6.x or both." & @CRLF & @CRLF & _
            "You will be asked first if you have WPDOS 5.1," & @CRLF & _
            "then if you have WPDOS 6.x. If you have both," & @CRLF & _
            "WPDOS 5.1 setup will complete before WPDOS 6.x" & @CRLF & _
            "setup begins." & @CRLF & @CRLF & _
            "You must know the name of the directory that" & @CRLF & _
            "contains your WPDOS program." & @CRLF & @CRLF & _
            "If your .SET files are in different directories" & @CRLF & _
            "from the WPDOS program itself, you may need to" & @CRLF & _
            "install printer drivers by hand.")
    If $a = 2 Then Ended()
EndFunc   ;==>PtrDriverMsg

Func AskWP51()
    $nowp5 = 0
    $a = MsgBox(270371, $t & " - Install driver in WPDOS 5.1?", "Do you have WordPerfect for DOS 5.1?")
    If $a = 2 Then Ended()
    If $a = 7 Then
        $nowp5 = 1
        Return
    EndIf
    If $a = 6 Then
        $a = MsgBox(270401, $t, "WPDOS 5.1 installation will begin.")
        If $a = 2 Then AskWP51()
    EndIf
EndFunc   ;==>AskWP51

Func FindWP51()
    If $nowp5 = 1 Then Return
    $wp5dir = ""
    If FileExists("c:\wp51\wp.exe") Then
        If FileExists("c:\wp51\wp{wp}.set") Then $wp5dir = "C:\WP51"
    EndIf
;~ ;    MsgBox(0, $t, $wp5dir)
    If FileExists("c:\corel\wp51\wp.exe") Then
        If FileExists("c:\corel\wp51\wp{wp}.set") Then $wp5dir = "C:\Corel\WP51"
    EndIf
    $wp5read = RegRead("HKLM\SOFTWARE\WPDOS.org", "WP51")
    ;MsgBox(0,'', "Wp5read is " & $wp5read)
    If $wp5read <> "" Then $wp5dir = $wp5read
    If Not $wp5dir = "" Then
        $a = MsgBox(270371, $t, "WP 5.1 seems to be in " & $wp5dir & "." & @LF & @LF & "Is this correct?")
        If $a = 2 Then Ended()
        If $a = 7 Then $wp5path = ""
        If $a = 6 Then
            $wp5path = $wp5dir
            ;           MsgBox(270336, $t, "OK, here's where we start")
        EndIf
    EndIf
EndFunc   ;==>FindWP51

Func GetWP51Dir()
    If $nowp5 = 1 Then Return
    While $wp5path = ""
        If $wp5path = "" Then
            $ans = _InputBoxOnTop($t, "Enter WPDOS 5.1 directory (e.g. c:\wp51): ", "", "", -1, 140)
            If $err Then Ended()
            $wp5path = $ans
            $dc = StringMid($wp5path, 1, 1)
            If StringIsAlpha($dc) = 0 Then
                $a = MsgBox(262145, $t, "You must enter a drive letter and path (e.g. c:\wp51)")
                If $a = 2 Then Ended()
                $wp5path = ""
            ElseIf StringMid($wp5path, 2, 2) <> ":\" Then
                $a = MsgBox(262145, $t, "You must enter a drive letter and path (e.g. c:\corel\wp51)")
                If $a = 2 Then Ended()
                $wp5path = ""
            ElseIf Not FileExists($wp5path) Then
                MsgBox(0, $t, "Directory not found.")
                $wp5path = ""
            ElseIf Not FileExists($wp5path & "\wp{wp}.set") Then
                If FileExists($wp5path & "\wp.exe") Then
                    MsgBox(0, $t, "WPDOS 5.1 program found, but required .SET file not found.")
                    $wp5path = ""
                Else
                    MsgBox(0, $t, "WPDOS51 not found in " & $wp5path)
                    $wp5path = ""
                EndIf
            EndIf
        EndIf
    WEnd
EndFunc   ;==>GetWP51Dir

Func WP51AllFile()
    If $nowp5 = 1 Then Return
    ;; Run Showset.exe to get WP51 printer file path
    If Not FileExists(@TempDir & "\showset.exe") Then
        FileInstall("V:\DirMonFiles\showset.exe", @TempDir & "\showset.exe", 1)
    EndIf
    If $tameinst = 1 Then
        FileCopy(@SystemDir & "\autoexec.nt", @TempDir & "\autoexec.nt-save", 1)
        FileInstall("v:\DirMonFiles\autoexec.notame", @SystemDir & "\autoexec.nt", 1)
    EndIf
    RunWait(@ComSpec & " /c " & 'showset.exe ' & $wp5path & '\wp{wp}.set > set51.txt', @TempDir, @SW_MINIMIZE)
    Sleep(100)
    If $tameinst = 1 Then
        FileCopy(@TempDir & "\autoexec.nt-save", @SystemDir & "\autoexec.nt", 1)
    EndIf
    Sleep(100)
    $pfpath = ""
    $setfile = FileOpen(@TempDir & "\set51.txt", 0)
    If $pfline <> -1 Then
        $stringfound = 0
        While 1
            $pfline = FileReadLine($setfile)
            If @error Then ExitLoop
            If StringInStr($pfline, "Printer Files") Then
                $stringfound = 1
                ExitLoop
            EndIf
            If @error = -1 Then ExitLoop
        WEnd
        If $stringfound = 0 Then
            ;MsgBox(48, $t, "Printer file location could not be determined. Exiting.")
            ;Exit
            ;;;;;;;;;;;;;;;;;;;;;
            $ploop = 1
            While $ploop = 1
                $ans = _InputBoxOnTop($t, "Enter WP51 printer file location:", "", "", -1, 130)
                If $err Then Ended()
                $pfpath = $ans
                If $pfpath = "" Then
                    MsgBox(270384, $t, "Cannot proceed without printer file location.")
                    Ended()
                EndIf
                $ck = FileExists($pfpath)
                If $ck = 1 Then
                    ExitLoop
                Else
                    MsgBox(270384, $t, "Invalid location specified.")
                EndIf
                ;;;;;;;;;;;;;
            WEnd
        EndIf
        FileClose($setfile)
    Else
        MsgBox(16, $t, 'FileOpen error')
        Exit
    EndIf
    FileDelete(@TempDir & "\set51.txt")
    Sleep(10)
    ;;;;;;;;;;;;;;;;;;;;;;;
    If $pfpath = "" Then
        If Not StringInStr($pfline, "\") Then
            $pfpath = $wp5path
        Else
            $pfpath = StringTrimLeft($pfline, 35)
        EndIf
    EndIf
    ;;;;;;;;;;;;;;;;;;;;
    ;   MsgBox(0, $t, "Printer file path is: " & $pfpath)
    ;; Copy WP51 .All file
    If Not FileExists($pfpath & "\wp51gscr.all") Then
        ;   MsgBox(0, $t, "Can't find ALL file.")
        FileInstall("v:\DirMonFiles\wp51gscr.all", $pfpath & "\wp51gscr.all", 1)
    EndIf
    ;Sleep(100)

EndFunc   ;==>WP51AllFile

Func WP51MacroRun()
    If $nowp5 = 1 Then Return
    ;; Create InstGS5 macro and run WP to set it up
    FileInstall("V:\DirMonFiles\inst5mac.txt", @TempDir & "\inst5mac.txt", 1)
    _FileWriteToLine(@TempDir & "\inst5mac.txt", 1, "{ASSIGN}gsport~" & $dmtmppath & "\wpdos.ps~", 0)
    If Not FileExists(@TempDir & "\macascii.exe") Then
        FileInstall("V:\DirMonFiles\macascii.exe", @TempDir & "\macascii.exe", 1)
    EndIf
    If Not FileExists(@TempDir & "\wp.mrs") Then
        FileInstall("V:\DirMonFiles\wp.mrs", @TempDir & "\wp.mrs", 1)
    EndIf
    If $tameinst = 1 Then
        FileCopy(@SystemDir & "\autoexec.nt", @TempDir & "\autoexec.nt-save", 1)
        FileInstall("v:\DirMonFiles\autoexec.notame", @SystemDir & "\autoexec.nt", 1)
    EndIf
    RunWait(@ComSpec & " /c " & 'macascii.exe /iinst5mac.txt /oinstgs51.wpm /mwp', @TempDir, @SW_MINIMIZE)
    If $tameinst = 1 Then
        FileCopy(@TempDir & "\autoexec.nt-save", @SystemDir & "\autoexec.nt", 1)
    EndIf
    FileCopy(@TempDir & "\instgs51.wpm", $drv & "\instgs51.wpm", 1)
    $a = MsgBox(270401, $t, "WPDOS 5.1 will now open, ask you two questions, and then close.")
    If $a = 2 Then Ended()
    RunWait(@ComSpec & " /c " & $wp5path & '\wp.exe /dl /ne /m-' & $drv & '\instgs51.wpm', $wp5path, @SW_MAXIMIZE)
    ;RunWait(@ComSpec & " /c " & $wp5path & '\wp.exe /dl /ne /m-' & @TempDir & '\instgs51.wpm', $wp5path, @SW_MAXIMIZE)
    RegWrite("HKLM\Software\WPDOS.org", "WP51", "REG_SZ", $wp5path)
    FileDelete(@TempDir & "\inst5mac.txt")
    Sleep(10)
    FileDelete($drv & "\instgs51.wpm")
    Sleep(10)
EndFunc   ;==>WP51MacroRun

Func AskWP6()
    $msgnum = 270627
    If $nowp5 = 1 Then $msgnum = 270371
    $a = MsgBox($msgnum, $t & " - Install driver in WPDOS 6.x?", "Do you have WordPerfect for DOS 6.0, 6.1, or 6.2?")
    If $a = 2 Then Ended()
    If $a = 6 Then
        $a = MsgBox(270401, $t, "WPDOS 6.x installation will begin.")
        If $a = 2 Then AskWP6()
    EndIf
    If $a = 7 Then
        InstComplete()
        Exit
    EndIf
EndFunc   ;==>AskWP6

Func FindWP6()
    $wp6dir = ""
    If FileExists("c:\wp60c\wp.exe") Then
        If FileExists("c:\wp60c\wp{wpc}.set") Then $wp6dir = "C:\WP60c"
    EndIf
    If FileExists("c:\wp61\wp.exe") Then
        If FileExists("c:\wp61\wp{wpc}.set") Then $wp6dir = "C:\WP61"
    EndIf
    If FileExists("c:\wp62\wp.exe") Then
        If FileExists("c:\wp62\wp{wpc}.set") Then $wp6dir = "C:\WP62"
    EndIf
    If FileExists("c:\corel\wp62\wp.exe") Then
        If FileExists("c:\corel\wp62\wp{wpc}.set") Then $wp6dir = "C:\corel\WP62"
    EndIf
    ;;;;;MsgBox(0, $t, $wp6dir)
    $wp6read = RegRead("HKLM\SOFTWARE\WPDOS.org", "WP6x")
    ;MsgBox(0,'', "Wp6read is " & $wp6read)
    If $wp6read <> "" Then $wp6dir = $wp6read
    If Not $wp6dir = "" Then
        $a = MsgBox(270627, $t, "WPDOS 6 seems to be in " & $wp6dir & "." & @LF & @LF & "Is this correct?")
        If $a = 2 Then Ended()
        If $a = 7 Then $wp6path = ""
        If $a = 6 Then
            $wp6path = $wp6dir
        EndIf
    EndIf
EndFunc   ;==>FindWP6

Func GetWP6Dir()
    While $wp6path = ""
        If $wp6path = "" Then
            ;; Get WP6 directory
            ;$wp6path = InputBox($t, "Enter WPDOS 6 directory (e.g. c:\wp61): ", "", "", -1, 140)
            $ans = _InputBoxOnTop($t, "Enter WPDOS 6 directory (e.g. c:\wp61): ", "", "", -1, 140)
            If $err Then Ended()
            $wp6path = $ans
            ;If @error = 1 Then Ended()
            ;;; change this to Cancelled
            $dc = StringMid($wp6path, 1, 1)
            If StringIsAlpha($dc) = 0 Then
                $a = MsgBox(262145, $t, "You must enter a drive letter and path (e.g. c:\wp61)")
                If $a = 2 Then Ended()
                $wp6path = ""
            ElseIf StringMid($wp6path, 2, 2) <> ":\" Then
                $a = MsgBox(262145, $t, "You must enter a drive letter and path (e.g. c:\corel\wp61)")
                If $a = 2 Then Ended()
                $wp6path = ""
            ElseIf Not FileExists($wp6path) Then
                MsgBox(0, $t, "Directory not found.")
                $wp6path = ""
            ElseIf Not FileExists($wp6path & "\wp{wpc}.set") Then
                If FileExists($wp6path & "\wp.exe") Then
                    MsgBox(0, $t, "WPDOS 6 program found, but required .SET file not found.")
                    $wp6path = ""
                Else
                    MsgBox(0, $t, "WPDOS 6 not found in " & $wp6path)
                    $wp6path = ""
                EndIf
            EndIf
        EndIf
    WEnd
EndFunc   ;==>GetWP6Dir


Func WP6AllFile()
    ;; Copy WP6 .All file
    If Not FileExists($wp6path & "\wp60gscr.all") Then
        ;   MsgBox(0, $t, "Can't find ALL file.")
        FileInstall("v:\DirMonFiles\wp60gscr.all", $wp6path & "\wp60gscr.all", 1)
        ;   MsgBox(0, $t, "Copied ALL file to " & $wp6path)
    EndIf
    ;MsgBox(0, $t, "ALL file already in " & $wp6path)
EndFunc   ;==>WP6AllFile

Func WP6MacroRun()
    FileInstall("V:\DirMonFiles\wpdostmp.wpm", @TempDir & "\wpdostmp.wpm", 1)
    FileInstall("V:\DirMonFiles\instgs6.txt", $wp6path & "\instgs6.txt", 1)
    _FileWriteToLine($wp6path & "\instgs6.txt", 1, "ASSIGN(PP;" & Chr(34) & $dmtmppath & '\wpdos.ps' & Chr(34) & ")", 0)
    MsgBox(270401, $t, "WPDOS 6 will now open, ask you some questions, and then close.")
    If $a = 2 Then Ended()
    RunWait(@ComSpec & " /c " & $wp6path & '\wp.exe /ne /nf /m-' & @TempDir & '\wpdostmp.wpm', $wp6path, @SW_MAXIMIZE)
    FileDelete(@TempDir & "\wpdostmp.wpm")
    Sleep(10)
    FileDelete($wp6path & "\instgs6.txt")
    Sleep(10)
    FileDelete($wp6path & "\instgs6.wpm")
    Sleep(10)
    RegWrite("HKLM\Software\WPDOS.org", "WP6x", "REG_SZ", $wp6path)
EndFunc   ;==>WP6MacroRun

;; End WP Setup Routines
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; InputBox on Top routine by HereWasPlato
;~ Global $err = 0
;~ $ans = _InputBoxOnTop("Title", "Prompt")
;~ MsgBox(0, "Returned", $ans)
;~ MsgBox(0, "@error", $err)

Dim $IBTitle, $IBPrompt, $IBDefault = "", $IBpassword_char = "", $IBWidth, $IBHeight = 140, $IBLeft, $IBTop, $IBTimeOut
Dim $file, $line1, $line2, $line3

Func _InputBoxOnTop($IBTitle, $IBPrompt, $IBDefault = "", _
        $IBpassword_char = "", $IBWidth = -1, $IBHeight = -1, _
        $IBLeft = Default, $IBTop = Default, $IBTimeOut = "")
    Local $file = FileOpen(EnvGet("temp") & "\InputBoxOT.au3", 2)
    If $file = -1 Then Return;if error, give up

    Local $line1 = 'AutoItSetOption(' & '"WinWaitDelay", 0' & ')'
    Local $line2 = 'WinWait("' & $IBTitle & '", "' & $IBPrompt & '")'
    Local $line3 = 'WinSetOnTop("' & $IBTitle & '", "' & $IBPrompt & '" ,1)'
    FileWrite($file, $line1 & @CRLF & $line2 & @CRLF & $line3)
    FileClose($file)

    Run(@AutoItExe & " /AutoIt3ExecuteScript " & EnvGet("temp") & "\InputBoxOT.au3")

    Local $ans = InputBox($IBTitle, $IBPrompt, $IBDefault, _
            $IBpassword_char, $IBWidth, $IBHeight, _
            $IBLeft, $IBTop, $IBTimeOut)
    If @error Then
        $ans = @error
        While Not FileDelete(EnvGet("temp") & "\InputBoxOT.au3")
            Sleep(10)
        WEnd
        SetError($ans)
        $ans = ""
        Return $ans
    EndIf

    While Not FileDelete(EnvGet("temp") & "\InputBoxOT.au3")
        Sleep(10)
    WEnd

    Return ($ans)
EndFunc   ;==>_InputBoxOnTop

;  Function stored for future use
;~ Func ChangeMyLabel()

;~  If $switchlabel = $slbl1 Then
;~      $switchlabel = $slbl2
;~  ElseIf $switchlabel = $slbl2 Then
;~      $switchlabel = $slbl1
;~  EndIf
;~  GUICtrlSetData($dl_label, $switchlabel)
;~ EndFunc   ;==>ChangeMyLabel