<scriptlet>

<implements type='automation'>
	<method name='OpenTextFile'/>
	<property name='ShowConsole'/>
	<property name='ReadOnly'/>
	<property name='Encoding'/>
	<property name='TextType'/>
	<property name='Arguments'>
		<put internalName='put_Arguments'/>
	</property>
</implements>

<script language='vbs'>
Option Explicit

Const ShowConsole = 0
Const ReadOnly = True
Const Encoding = "UTF-8"

Dim TextType, options

Dim sh, fs, tmpfile

Set sh = CreateObject("WScript.Shell")
Set fs = CreateObject("Scripting.FileSystemObject")

Sub put_Arguments(Arguments)
	If Not IsEmpty(Arguments) Then Execute Arguments
	If InStr(options, "-t html") Then
		TextType = "HTML"
	ElseIf InStr(options, "-t markdown") Then
		TextType = "MD"
	End If
End Sub

Class TempFile
	Private fs, path

	Private Sub Class_Initialize
		Set fs = CreateObject("Scripting.FileSystemObject")
	End Sub

	Private Sub Class_Terminate
		If Not IsEmpty(path) Then fs.DeleteFile path
	End Sub

	Public Function CreatePath(suffix)
		path = fs.GetSpecialFolder(2) & "\" & Mid(CreateObject("Scriptlet.TypeLib").Guid, 2, 36) & suffix
		CreatePath = path
	End Function
End Class

Function OpenTextFile(path)
	Dim ex, temp, ending
	temp = path & "*"
	If InStr(temp, ".doc*") <> 0 Or InStr(temp, ".dot*") <> 0 Then
		Set tmpfile = New TempFile
		temp = tmpfile.CreatePath(".*")
		path = Replace(path, "\\?\UNC\", "\\")
		path = Replace(path, "\\?\", "")
		sh.Run """%WinMergeRoot%\B2XTranslator\bin\doc2x.exe"" """ & path & """ -o """ & temp & """", 0, True
		For Each ending In Split(".docx .docm .dotx .dotm")
			path = Replace(temp, ".*", ending)
			If fs.FileExists(path) Then Exit For
		Next
		options = options & " --from=docx"
	End If
	Set ex = sh.Exec("""pandoc.exe"" " & options & " """ & path & """")
	If ex.StdOut.AtEndOfStream Then
		Set OpenTextFile = ex.StdErr
	Else
		Set OpenTextFile = ex.StdOut
	End If
End Function
</script>
</scriptlet>
