'' wp-lo.vbs - uses LibreOffice to convert a WordPerfect file to Word or PDF format
'' version 3.0.8 - 21 February 2014
'' By Edward Mendelson http://wpdos.org

Option Explicit ' Do not change this line!

''''''''''''''''''''''''' USAGE AND PARAMETERS ''''''''''''''''''''''''''''''''''''''''''''''

'' Usage: wp-lo.vbs [ <input-filespec> ] [ <output-filespec> | PDF | DOC ]

'' Defaults to converting a WordPerfect file to DOC format. If the filename of the
''    script contains "PDF" it will convert to PDF format instead. If the filename of
''    the script contains "View" the converted DOC or PDF will open in the default
''    application for that format. 

'' The filename option described above overrides the user options described below.

'' Parameters are optional, but if Parameter 2 is used, Parameter 1 is also required; 

'' If Parameter 1 or 2 includes a path or filename with a space character, enclose the 
''		parameter in quotation marks

'' Parameter 1: either blank or <input-filespec>
''		<input-filespec> = full path a WPDOS file
'' Parameter 2: either blank or <output-filespec> or PDF or DOC
''   EITHER:
'' 		 <output-filespec> either full path of the exported output file (ending in .DOC or .PDF),
''     or the filename only of the exported output file, which will be saved in the same
''	   directory as the import file
''   OR:
'' 	   DOC or PDF = used to specify <input-filespec>.doc (or .pdf) as the output filename

''''''''''''''''''''''''' USER-SELECTABLE OPTIONS '''''''''''''''''''''''''''''''''''''''''

''''' Export as PDF, not Word (.DOC) format ''''''

	'' This script can be set to create PDF files instead of DOC files by default.
	'' To turn on this option, in the first line below, change PDFExport from "No" to "Yes".
		
	Dim PDFExport	: PDFExport = "No"

''''' Option to turn off "processing takes time" prompt '''''

	'' If you want to turn off the prompt that says "File processing can take some time",
	'' change "On" to "Off" (in quotation marks) in the line below. Default setting is "On".

	Dim TakesTimePrompt : TakesTimePrompt = "On"

''''' Option to turn off prompt when overwriting an existing file '''''

  '' IMPORTANT: If you want to turn off the prompt when overwriting existing files
  '' change "On" to "Off" (in quotation marks) in the line below this block.
  
	Dim PromptForOverwrite : PromptForOverwrite = "On"
	
''''' Open output file in default editor/viewer ''''''

	'' If you want to open the converted file in your default application for .DOC
	'' or PDF files, set this option to "Yes" (to open the converted file automatically)
	'' or to "Ask" (to be prompted before the file is opened) or "No":
	
	Dim ViewFile : ViewFile = "Ask"

''''' Option for silent operation (no prompts; default filename; overwrite on) '''''

  '' IMPORTANT: If this option is set to "Yes", then the script will not display
  '' any prompts or other messages - although it WILL display error messages that
  '' warn about configuration errors, missing files, or other problems.
  '' WARNING: If this option is set to "Yes", the script will overwrite an existing
  '' output file with no warning! Make sure you understand this!
  '' To turn off all warnings and other non-error messages, set this option to "Yes":
  
	Dim Silent : Silent = "No"

'''''''''''''''''''''' END OF USER OPTIONS '''''''''''''''''''''''''''''''''''''''''''''''''''

Dim sInFile, sOutFile, sFilename
Dim sApp, sFSpec, sInPath, sOutPath, sOutURL, winAddr, WshShell, defaultExt
Dim args, num, msgTxt, styleBtn, response, userIn, msgEnd
'Dim defaultExt : defaultExt = ".doc"
Dim nameString : nameString = "LibreOffice"
Dim titleTxt : titleTxt = "Export WP file using " & nameString
Dim strReg, strAppPath, strTmpDir, strFull, strFolder, strName
Dim strFileTemp, strOutTemp, cvtTo, doDelete, doView, oTmp
Dim objShell : Set objShell = CreateObject("Wscript.Shell")
Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
Dim CurDir : CurDir = oFSO.GetParentFolderName(Wscript.ScriptFullName)
Dim strScript : strScript = LCase(Wscript.ScriptName)

'' add instr <> 0 test for pdf in script name to automate PDF 
'' add test for view in script name to automate view=yes

GetAppPath
UserOptions
GetFileNames
CopyConvert
OpenForEditing
WScript.Quit

Sub GetAppPath
	On Error Resume Next
  strReg = objShell.RegRead("HKCR\Software\LibreOffice\LibreOffice\Path")
   	If Err.Number <> 0 Then
				MsgBox "Unable to find LibreOffice on this system. Quitting.", _
					vbOKOnly + VbMsgBoxSetForeground, titleTxt
    		wScript.Quit
		End If
  strAppPath = strReg & "program\soffice.exe"
  If oFSO(FileExists(strAppPath)) Then
  Else
  		MsgBox "LibreOffice application missing or not properly installed. Quitting.", _
					vbOKOnly + VbMsgBoxSetForeground, titleTxt
    	wScript.Quit
  End If
  objShell.CurrentDirectory = strReg & "URE\bin"
  strTmpDir = objShell.ExpandEnvironmentStrings("%temp%")
End Sub

Sub UserOptions
  Select Case LCase(PDFExport) 
  		Case "yes" 
  			DoPDF
  		Case "no" 
  			DoDoc
  		Case Else
  			MsgBox "Error: The PDFExport variable must be either 'Yes' or 'No'." + vbCR + _
  				vbCR + "You entered: '" + pdfExport + "'.", vbOKOnly + VbMsgBoxSetForeground,_
  			  titleTxt
  			WScript.Quit
  End Select
  titleTxt = "Export WP file to " + sApp + " using " + nameString
  If LCase(TakesTimePrompt) = "on" Then
  	ElseIf LCase(TakesTimePrompt) = "off" Then
  	Else
  		MsgBox "Error: The TakesTimePrompt variable must be either 'On' or 'Off'." + _
  			vbCR + vbCR + "You entered: '" + TakesTimePrompt + "'.", _
  			vbOKOnly + VbMsgBoxSetForeground, titleTxt
  		WScript.Quit
  	End If
  If LCase(PromptForOverwrite) = "off" Then
  	ElseIf LCase(PromptForOverwrite) = "on" Then
  	Else 
  		MsgBox "Error: The PromptForOverwrite variable must be either 'On' or 'Off'." _ 
  				+ vbCR + vbCR + "You entered: '" + PromptForOverwrite + "'.", _
  				vbOKOnly + VbMsgBoxSetForeground, titleTxt
  		WScript.Quit
  End If
	Select Case LCase(ViewFile) 
  		Case "yes" 
  			doView = "yes"
  		Case "no" 
  			doView = "no"
  		Case "ask"
  			doView = "yes"
  		Case Else
  			MsgBox "Error: The PDFExport variable must be either 'Yes' or 'No'." + vbCR + _
  				vbCR + "You entered: '" + pdfExport + "'.", vbOKOnly, _
  				"Export WP file using LibreOffice"
    		WScript.Quit
  End Select
	If LCase(Silent) = "no" Then
  	ElseIf LCase(Silent) = "yes" Then
  	Else
  		MsgBox "Error: The Silent variable must be either 'Yes' or 'No'." + vbCR + vbCR + _
  				"You entered: '" + Silent + "'.", vbOKOnly + VbMsgBoxSetForeground, titleTxt
  		WScript.Quit
  	End If
  	
  If inStr(strScript, "pdf") <> 0 Then
  		DoPDF
  		If inStr(strScript, "doc") <> 0 Then
  			DoubleName
  		End If
  End If
  
  If inStr(strScript, "doc") <> 0 Then
  	DoDoc
  End If
  
  If inStr(strScript, "view") <> 0 Then
  	doView = "yes"
  	ViewFile = "yes"
	End If
	
End Sub 'UserOptions

Sub GetFileNames
  Set args = WScript.Arguments
  num = args.Count
  If num = 0 Then
  	MsgBox "Error: Drop a WP file on this script icon, or use a filename as a command-line parameter.", _
  			vbOKOnly + VbMsgBoxSetForeground, titleTxt
  	wScript.Quit
  End If
  
  sInFile = args.Item(0)
  titleTxt = "Export WP file to " + sApp + " with " + nameString
  ' assume filespec in script directory if no path entered
     If InStr(sInFile, "\") = 0 Then
           	sInFile = CurDir + "\" + sInFile
   	 End If
  
  	If oFSO.FileExists(sInFile) Then
    	Else
       MsgBox "Error: The specified input file does not exist.", vbOKOnly, titleTxt
       WScript.Quit
  	End If
   	
   	 Dim objInFile
   	 Set objInFile = oFSO.GetFile(sInFile)
   	 sInPath = objInFile.ParentFolder
   	 'MsgBox sInPath
  	
  If num >= 2 Then 
     sOutFile = args.Item(1)
     	If LCase(sOutFile) = "pdf" Then
    		sOutFile = sInfile + ".pdf"
    		DoPDF
    	ElseIf LCase(sOutFile) = "doc" Then
    		sOutFile = sInfile + ".doc"
    		DoDoc
    	ElseIf LCase(Right(sOutFile,4)) = ".doc" Then
    		DoDoc
     	ElseIf LCase(Right(sOutFile,4)) = ".pdf" Then
    		DoPDF
    	Else
    			MsgBox "Output file parameter must be a valid filename with the extension .DOC or .PDF," + vbCR + _
    				"or the three-letter parameter DOC or PDF.", vbOKOnly + vbMsgBoxSetForeground, _
    				titleTxt
    			WScript.Quit
    	End If
    	'' if no filename specified, then use same folder as input file
    	If InStr(sOutFile, "\") = 0 Then
    		sOutFile = sInPath + "\" + sOutFile
    		sOutFile = Replace(sOutFile, "\\", "\")
    	End If
    	
    	titleTxt = "Export WP file to " + sApp + " with " + nameString
  Else
  	 		sOutFile = sInFile + defaultExt
  End If
  
  If oFSO.FolderExists(sOutFile) Then
  	MsgBox "Error: The specified output file '" + sOutFile + "' is the name of a folder." _
  		+ vbCR + vbCr + "Please specify a valid filename instead.", _
  		vbOKOnly + VbMsgBoxSetForeground, titleTxt
  	WScript.Quit
  End If
  If LCase(Silent) = "no" Then
    msgTxt = nameString + " will export WP file " + UCase(sInFile) + " to " + sApp + " file:" + _
    	vbCR + vbCR + sOutFile + vbCR + vbCR + "Use different filename for converted file?"
    styleBtn = VBYesNoCancel + VBDefaultButton2 + VBInformation  + VbMsgBoxSetForeground
    response = MsgBox(msgTxt, StyleBtn, titleTxt)
    If response = VBYes Then
        GetsOutFile(sFilename)
    Else
    	If response = VBCancel Then
    		CancelQuit
    	End If
    End If
  End If
  
  While LCase(Right(sOutFile,4)) <> defaultExt 
  		MsgBox "You may not change the extension of the output file from " + defaultExt, _
  				vbOKOnly, titleTxt
  		Dim iStrLen : iStrLen = Len(sOutFile)
  		sOutFile = Left(sOutFile,(iStrLen -4)) + defaultExt
  		GetsOutFile(sOutFile)
  Wend
  
  While UCase(sInFile) = UCase(sOutFile)
  msgTxt = "Source file and converted file must have different names." 
  styleBtn = VBOK + VBCritical
  response = MsgBox(msgTxt, StyleBtn, titleTxt)
  	If response = VBCancel Then
  		wScript.Quit
  	End If
  GetsOutFile(sFilename)
  If Len(sOutFile)  = 0 Then
  	wscript.Quit
  End If
  Wend
  
  If LCase(Silent) = "no" Then
    If LCase(PromptForOverwrite) = "on" Then
      If oFSO.FileExists(sOutFile) Then
      	msgTxt = "Output file " + sOutFile + " exists!" + vbCR + vbCR + _
      			"Overwrite existing file?"
      	styleBtn = VBYesNo + VBDefaultButton2 + VBExclamation + _
      			VbMsgBoxSetForeground + vbSystemModal
      	Wscript.Sleep 100
      	response = MsgBox(msgTxt, styleBtn, titleTxt)
        If response = VBNo Then
        	doDelete = "no"
        	GetsOutFile(sOutFile)
       		'CancelQuit
       	Else
       		doDelete = "yes"
        End If
      End If
    End If
  Else
  	If oFSO.FileExists(sOutFile) Then
  		oFSO.DeleteFile(sOutFile)
  	End If
  End If
  
  strFull = oFSO.GetAbsolutePathName(sInFile)
  strFolder = oFSO.GetParentFolderName(sInFile)
  strName = oFSO.GetFileName(sInFile)
  strFileTemp = strTmpDir & "\" & strName & ".wpd"
  strOutTemp = strTmpDir & "\" & strName & defaultExt
End Sub 'GetFileNames

Sub CopyConvert
	If LCase(Silent) = "no" Then
    If LCase(TakesTimePrompt) = "on" Then 
      response = MsgBox("File conversion may take time. Press OK, and please wait.", _
      			vbOK + VbMsgBoxSetForeground, titleTxt)
      If response = vbCancel Then
      		wScript.Quit
      End If
    End If
  End If
  Const OverwriteExisting = True
  oFSO.CopyFile sInFile, strFileTemp, OverwriteExisting
  ' next lines test for read-only temp file
  Const ReadOnly = 1 
  Set oTmp = oFSO.GetFile(strFileTemp)  
  If oTmp.Attributes AND ReadOnly Then
  	oTmp.Attributes = oTmp.Attributes XOR ReadOnly
  End If
  ' Return =
  objShell.Run Chr(34) & strAppPath & Chr(34) & _
  	" --invisible --convert-to " & cvtTo & " --outdir " & strTmpDir & " " & strFileTemp, 0, True
  If doDelete = "yes" Then
  	If oFSO.FileExists(sOutFile) Then
  		oFSO.DeleteFile(sOutFile)
  	End If
	End If
	
	Wscript.Sleep 100
	
  oFSO.MoveFile strOutTemp, sOutFile
  oFSO.DeleteFile strFileTemp
  If LCase(Silent) = "no" Then
  	If doView = "no" Then
    	MsgBox sOutFile & " written to disk.", vbOKOnly, titleTxt
    End If
	End If	
End Sub 'CopyConvert

Sub OpenForEditing
	If doView = "yes" then
		If LCase(ViewFile) = "yes" Then
			objShell.Run Chr(34) & sOutFile & Chr(34), 1, false
		Else
    	If LCase(Silent) = "no" Then
        If PDFExport = 0 Then 
        		msgEnd = "for editing?"
        ElseIf PDFExport = 1 Then
        		msgEnd = "for viewing?"
        End If
        msgTxt = "Exported file saved as " + sOutFile + vbCR + vbCR + _
        	"Open exported file " + msgEnd
        styleBtn = VBYesNo + VBDefaultButton2 + VBInformation + VbMsgBoxSetForeground
        response = MsgBox(msgTxt, styleBtn, titleTxt)
        If response = VBYes Then
        		objShell.Run Chr(34) & sOutFile & Chr(34), 1, false
        End If
    	Else
      	objShell.Run Chr(34) & sOutFile & Chr(34), 1, false
    	End If
 		End If
	End If
End Sub 'OpenForEditing

Sub DoDoc
 'sOutFile = sInfile + ".doc"
	PDFExport = 0
	defaultExt = ".doc"
	cvtTo = "doc:"+chr(34)+"MS Word 97"+chr(34)
	sApp = "Word"
End Sub 'DoDoc

Sub DoPDF
	PDFExport = 1
	defaultExt = ".pdf"
	cvtTo = "pdf"
	sApp = "PDF"
End Sub 'DoPDF

Function CancelQuit
	MsgBox "Macro cancelled. Your file was not converted.", _
				vbOKOnly + VbMsgBoxSetForeground, titleTxt
    wScript.Quit
End Function 'CancelQuit

Function GetsOutFile(sFilename)
userIn = InputBox("Enter path and filename for converted file: ", _ 
		titleTxt, sOutFile)
sOutFile = userIn
If Len(userIn)  = 0 Then
	wScript.Quit
End If
End Function 'GestsOutFile

Function DoubleName
	MsgBox "The name of this script cannot contain both DOC and PDF." _
  			+ vbCR + vbCR + "Quitting.", vbOKOnly + VbMsgBoxSetForeground, titleTxt
  wScript.Quit
End Function 'DoubleName