WBT2HTML v1.25
;==========================================================================================================================================
; WBT2HTML v1.25  20020824                                                                            (c) Detlev Dalitz 2001:07:29:00:00:00
;==========================================================================================================================================
; User information is placed at end of file.
;------------------------------------------------------------------------------------------------------------------------------------------

IntControl (73, 1, 0, 0, 0) ; Install the errorhandler.

iParamError = 0
If Param0
   GoSub GetParams
Else
   Goto AskParams
EndIf
If !iParamError
   GoSub DefineUDFs
   GoSub UserConfigurableInit
   GoSub ProgInit
   GoSub CollectColors
   GoSub CollectKeywords
   GoSub OpenReadSourceFile
   If UseAutoDelimiter Then GoSub CalculateDelimiters
   GoSub TagQuote
   GoSub TagComment
   GoSub TagOperatorMod
   GoSub TagOperator
   GoSub TagBracket
   GoSub TagSpecial
   GoSub TagWordNumber
   GoSub EncodeNamedEntities
   GoSub ColorizeWord
   GoSub ColorizeNumber
   GoSub ColorizeSpecial
   GoSub ColorizeOperator
   GoSub ColorizeOperatorMod
   GoSub ColorizeBracket
   GoSub ColorizeComment
   GoSub ColorizeQuote
   GoSub WriteCloseTargetFile
EndIf
If IntControl (77, 80, 0, 0, 0) Then Return (iParamError)
:CANCEL
Exit

;==========================================================================================================================================
:DefineUDFs
;------------------------------------------------------------------------------------------------------------------------------------------
If ItemLocate ("udfbytetohex", IntControl (77, 103, 0, 0, 0), @TAB) Then Goto skip_udfbytetohex
#DefineFunction udfByteToHex (Byte)
Return (StrCat (Num2Char (48 + (Byte >> 4) + (39 * ((Byte >> 4) > 9))), Num2Char (48 + (Byte & 15) + (39 * ((Byte & 15) > 9))))) ; lowercase
; Return (StrCat(Num2Char(48+(Byte>>4)+(7*((Byte>>4)>9))),Num2Char(48+(Byte&15)+(7*((Byte&15)>9))))) ; uppercase
#EndFunction
:skip_udfbytetohex
;------------------------------------------------------------------------------------------------------------------------------------------
If ItemLocate ("udffilechecksum", IntControl (77, 103, 0, 0, 0), @TAB) Then Goto skip_udffilechecksum
#DefineFunction udfFileChecksum (sFilename, iRequest)
If (VersionDLL () < "3.8hch") Then Return ("")
iBBSize = FileSizeEx (sFilename)
If !iBBSize Then Return ("")
iRequest = Min (2, Max (0, iRequest))
hBB = BinaryAlloc (iBBSize)
BinaryRead (hBB, sFilename)
sChecksum = BinaryChecksum (hBB, iRequest)
BinaryFree (hBB)
Return (sChecksum)
;..........................................................................................................................................
;   "iRequest" specifies the type of digest or CRC to generate,
;   and can be one of the following values:
;
;    Request   Meaning      Return string format (x = hex character)
;    -------   ----------   ----------------------------------------
;       0      MD5 digest   "xxxxxxxx-xxxxxxxx-xxxxxxxx-xxxxxxxx"
;       1      16-bit CRC   "xxxx"
;       2      32-bit CRC   "xxxxxxxx"
;
; Requires WinBatch version 2002h, 3.8hch.
;..........................................................................................................................................
#EndFunction
:skip_udffilechecksum
;------------------------------------------------------------------------------------------------------------------------------------------
If ItemLocate ("udffilecrc32", IntControl (77, 103, 0, 0, 0), @TAB) Then Goto skip_udffilecrc32
#DefineFunction udfFileCrc32 (sFilename)
iBBSize = FileSize (sFilename)
If !iBBSize Then Return (0)
AddExtender ("wwser34i.dll")
hBB = BinaryAlloc (iBBSize)
BinaryRead (hBB, sFilename)
iChecksum = pCheckBinary (IntControl (42, hBB, 0, 0, 0), BinaryEodGet (hBB) - 1, 32)
BinaryFree (hBB)
Return (iChecksum)
#EndFunction
:skip_udffilecrc32
;------------------------------------------------------------------------------------------------------------------------------------------
If ItemLocate ("udfgettemppath", IntControl (77, 103, 0, 0, 0), @TAB) Then Goto skip_udfgettemppath
#DefineFunction udfGetTempPath ()
ftemp = FileCreateTemp ("TMP")
FileDelete (ftemp)
TempPath = FilePath (ftemp)
Terminate (!DirMake (TempPath), "udfGetTempPath", StrCat ("Cannot access temporary folder:", @LF, TempPath))
Return (TempPath)
#EndFunction
:skip_udfgettemppath
;------------------------------------------------------------------------------------------------------------------------------------------
If ItemLocate ("udfdirgetlong", IntControl (77, 103, 0, 0, 0), @TAB) Then Goto skip_udfdirgetlong
#DefineFunction udfDirGetLong ()
Return (StrCat (FileNameLong (StrCat (DirGet (), ".")), "\"))
#EndFunction
:skip_udfdirgetlong
;------------------------------------------------------------------------------------------------------------------------------------------
If ItemLocate ("udsdisplaymsg", IntControl (77, 103, 0, 0, 0), @TAB) Then Goto skip_udsdisplaymsg
#DefineSubRoutine udsDisplayMsg (sMsgText)
If (RtStatus () == 10) Then wStatusMsg (StrCat (sLogo, sMsgText))
   Else BoxText (StrCat (sLogo, sMsgText))
sMsgText = ""
#EndSubRoutine
:skip_udsdisplaymsg
;------------------------------------------------------------------------------------------------------------------------------------------
If ItemLocate ("udfitemlisttofile", IntControl (77, 103, 0, 0, 0), @TAB) Then Goto skip_udfitemlisttofile
#DefineFunction udfItemListToFile (list, delimiter, filename)
If (list == "") Then Return (0)
list = StrReplace (list, delimiter, @CRLF)
hBB = BinaryAlloc (StrLen (list))
BinaryPokeStr (hBB, 0, list)
num = BinaryWrite (hBB, filename)
BinaryFree (hBB)
Return (num)
#EndFunction
:skip_udfitemlisttofile
;------------------------------------------------------------------------------------------------------------------------------------------
If ItemLocate ("udfisprimenumber", IntControl (77, 103, 0, 0, 0), @TAB) Then Goto skip_udfisprimenumber
#DefineFunction udfIsPrimeNumber (iNumber)
iLimit = Int (Sqrt (iNumber))
iIsPrime = 1
For i = 2 To iLimit
   iIsPrime = iNumber mod i
   If !iIsPrime Then Break
Next
Return (iIsPrime)
#EndFunction

:skip_udfisprimenumber
;------------------------------------------------------------------------------------------------------------------------------------------
If ItemLocate ("udfgetprimethisornext", IntControl (77, 103, 0, 0, 0), @TAB) Then Goto skip_udfgetprimethisornext
#DefineFunction udfGetPrimeThisOrNext (iNumber)
While !udfIsPrimeNumber (iNumber)
   iNumber = iNumber + 1
EndWhile
Return (iNumber)
#EndFunction

:skip_udfgetprimethisornext
;------------------------------------------------------------------------------------------------------------------------------------------
Return ; from DefineUDFs
;==========================================================================================================================================


;==========================================================================================================================================
;Procedures
;==========================================================================================================================================
:wbErrorHandler
wbError = LastError ()
wbErrorMsg = ""
wbErrorMsg = StrCat (wbErrorMsg, "LastError Value", @LF, '  = ', wbError, @LF)
If !wbError Then wbError = -1
wbErrorMsg = StrCat (wbErrorMsg, "LastError String", @LF, '  = "', IntControl (34, wbError, 0, 0, 0), '"', @LF)
; line in script that caused Error)
wbErrorMsg = StrCat (wbErrorMsg, "wbErrorHandlerLine", @LF, '  = "', wbErrorHandlerLine, '"', @LF)
; offset into script of error line, in bytes
wbErrorMsg = StrCat (wbErrorMsg, "wbErrorHandlerOffset", @LF, '  = ', wbErrorHandlerOffset, @LF)
; variable being assigned on error line, or "" If none
wbErrorMsg = StrCat (wbErrorMsg, "wbErrorHandlerAssignment", @LF, '  = ', wbErrorHandlerAssignment, @LF)
If (wbErrorhandlerassignment > "") Then %wbErrorhandlerassignment% = "eeek"
Message ("wbErrorHandler", wbErrorMsg)
Exit
;==========================================================================================================================================

;==========================================================================================================================================
:CollectColors ; collect names and rgb color values
sMsg = "Collecting colors ..."
udsDisplayMsg (sMsg)

; We use the default rgb color values as defined in WSINIT.DLL and try to update them from the Current User Registry.
sColorNameList = StrCat ("Keyword", @TAB, "Quote", @TAB, "Comment", @TAB, "Default Text", @TAB, "Background")
sColorValueList = StrCat ("0,0,255", @TAB, "255,0,0", @TAB, "0,128,0", @TAB, "0,0,0", @TAB, "255,255,255")

;--- Read colors for WIL files from WinBatch Studio Registry. -----------------------------------------------------------------------------
sRegKeySub = "Software\Wilson WindowWare\WinBatch Studio\Settings\File types\WIL Files"
If RegExistKey (@REGCURRENT, sRegKeySub)
   hRegKey = RegOpenKeyEx (@REGCURRENT, sRegKeySub, 1, "", "")
   ; Mode=1=KEY_QUERY_VALUE=Permission to query subkey data ; We only need read access.

   iColorCount = ItemCount (sColorNameList, @TAB)
   For iColor = 1 To iColorCount
      sColorNameItem = ItemExtract (iColor, sColorNameList, @TAB)
      sRegKeySub = StrCat ("[", sColorNameItem, "]")
      If RegExistValue (hRegKey, sRegKeySub)
         sColorValueItem = RegQueryValue (hRegKey, sRegKeySub)
         sColorValueList = ItemReplace (sColorValueItem, iColor, sColorValueList, @TAB)
      EndIf
   Next

   RegCloseKey (hRegKey)
   Drop (hRegKey, iColor, iColorCount, sColorNameItem, sColorValueItem)
EndIf
Drop (sRegKeySub)


;--- Additional colors from my own inspiration. -------------------------------------------------------------------------------------------
; Note: Force creating new HashTable if colors have changed.

sColorNameList = ItemInsert ("Operator", -1, sColorNameList, @TAB)
sColorValueList = ItemInsert ("000,048,128", -1, sColorValueList, @TAB)

sColorNameList = ItemInsert ("Bracket", -1, sColorNameList, @TAB)
sColorValueList = ItemInsert ("032,032,032", -1, sColorValueList, @TAB)

sColorNameList = ItemInsert ("Number", -1, sColorNameList, @TAB)
sColorValueList = ItemInsert ("096,000,000", -1, sColorValueList, @TAB)

sColorNameList = ItemInsert ("Special", -1, sColorNameList, @TAB)
sColorValueList = ItemInsert ("000,032,128", -1, sColorValueList, @TAB)


;--- Additional colors from WIL.CLR inifile. ----------------------------------------------------------------------------------------------
; for example: CON=128,0,128; EXT=255,0,255; CONSTANT=0,128,255; WED=0,128,0; UDF=128,096,048; OPERATOR=0,48,128

sFilenameWilClr = StrCat (DirHome (), "WIL.CLR")
sColorList = IniItemizePvt ("COLORS", sFilenameWilClr)
iColorCount = ItemCount (sColorList, @TAB)
For iColor = 1 To iColorCount
   sColorNameItem = ItemExtract (iColor, sColorList, @TAB)
   sColorValueItem = IniReadPvt ("COLORS", sColorNameItem, "000,000,000", sFilenameWilClr)
   sColorValueList = ItemInsert (sColorValueItem, -1, sColorValueList, @TAB)
   sColorNameList = ItemInsert (sColorNameItem, -1, sColorNameList, @TAB)
Next
Drop (iColorCount, sFilenameWilClr, sColorList, sColorNameItem, sColorValueItem, iColor)

;------------------------------------------------------------------------------------------------------------------------------------------
; Set all items to lower case.
; This is used later when comparing with lowercase keywords in hashbuffer.
sColorNameList = StrLower (sColorNameList)
; Delete duplicate names.
sNameTrimList = ""
sValueTrimList = ""
iCount = ItemCount (sColorNameList, @TAB)
For iColor = 1 To iCount
   sNameItem = ItemExtract (iColor, sColorNameList, @TAB)
   If (sNameItem > "")
      If !ItemLocate (sNameItem, sNameTrimList, @TAB)
         sNameTrimList = ItemInsert (sNameItem, -1, sNameTrimList, @TAB)
         sValueItem = ItemExtract (iColor, sColorValueList, @TAB)
         sValueTrimList = ItemInsert (sValueItem, -1, sValueTrimList, @TAB)
      EndIf
   EndIf
Next
sColorNameList = sNameTrimList
sColorValueList = sValueTrimList
Drop (iColor, iCount, sNameItem, sNameTrimList, sValueItem, sValueTrimList)

;------------------------------------------------------------------------------------------------------------------------------------------
If UseRGB
   ; delete all leading zeroes
   sColorValueList = ItemInsert ("", 0, sColorValueList, @TAB)
   sColorValueList = StrReplace (sColorValueList, @TAB, StrCat (",", @TAB, ","))
   sColorValueList = StrReplace (sColorValueList, ",0", ",")
   sColorValueList = StrReplace (sColorValueList, ",0", ",")
   sColorValueList = StrReplace (sColorValueList, ",,", ",0,")
   sColorValueList = StrReplace (sColorValueList, ",,", ",0,")
   sColorValueList = StrReplace (sColorValueList, StrCat (",", @TAB, ","), @TAB)
   sColorValueList = ItemRemove (1, sColorValueList, @TAB)
Else
   ; convert rgb to hex
   iColorCount = ItemCount (sColorValueList, @TAB)
   For iColor = 1 To iColorCount
      sRgbItem = ItemExtract (iColor, sColorValueList, @TAB)
      sColorValueItem = StrCat ("#", udfByteToHex (ItemExtract (1, sRgbItem, ",")))
      sColorValueItem = StrCat (sColorValueItem, udfByteToHex (ItemExtract (2, sRgbItem, ",")))
      sColorValueItem = StrCat (sColorValueItem, udfByteToHex (ItemExtract (3, sRgbItem, ",")))
      sColorValueList = ItemReplace (sColorValueItem, iColor, sColorValueList, @TAB)
   Next
EndIf
Drop (iColorCount, sColorValueItem, iColor, sRgbItem)

Return
;==========================================================================================================================================
:CollectKeywords
sMsg = "Collecting Keywords ..."
udsDisplayMsg (sMsg)

; Read my inifile in WinBatch system folder.
sFilenameW2HIni = StrCat (DirHome (), "wbt2html.ini")
If !FileExist (sFilenameW2HIni) Then Goto LabelCreateHashTable
If (IniReadPvt ("WBT2HTML", "FileVersion", "", sFilenameW2HIni) <> sProgVersion) Then Goto LabelCreateHashTable
sFilenameWilClr = IniReadPvt ("WIL", "ColorName", "", sFilenameW2HIni)
If (sFilenameWilClr == "") Then Goto LabelCreateHashTable
If !FileExist (sFilenameWilClr) Then Goto LabelCreateHashTable
If (IniReadPvt ("WIL", "ColorCRC", "", sFilenameW2HIni) <> udfFileCrc32 (sFilenameWilClr)) Then Goto LabelCreateHashTable
If !FileExist (IniReadPvt ("WIL", "HashName", "", sFilenameW2HIni)) Then Goto LabelCreateHashTable

sMsg = "Reading Keyword HashTable ..."
udsDisplayMsg (sMsg)

GoSub ReadIni ; Get the hash buffer filename and other definition values.

iBBHashSize = FileSizeEx (sFilenameBBHash)
If !iBBHashSize Then Goto LabelCreateHashTable

hBBHash = BinaryAlloc (iBBHashSize)
BinaryRead (hBBHash, sFilenameBBHash)
Drop (sFilenameWilClr, iBBHashSize, sFilenameW2HIni)
Return

; Create the Binary Buffer HashTable.
:LabelCreateHashTable
sMsg = "Creating Keyword HashTable ... be patient ..."
udsDisplayMsg (sMsg)
CurrentDir = DirGet ()
DirChange (udfGetTempPath ())
sFilenameBBHash = StrCat (udfDirGetLong (), "wil.hsh")
DirChange (DirHome ())
sFilenameWilClr = StrCat (udfDirGetLong (), "wil.clr")
DirChange (CurrentDir)
Drop (CurrentDir)

Terminate (!FileExist (sFilenameWilClr), "Error", "WBT2HTML.WBT needs a good WIL.CLR file with some Keywords in it ...")

GoSub InitIni
GoSub ReadIni

; Read keywords from WIL.CLR inifile and create HashTable.
sKeywordList = IniItemizePvt ("KEYWORDS", sFilenameWilClr)
iKeywordCount = ItemCount (sKeywordList, @TAB)

; Calculation rule: HashBufferSize = HashLoadFactor*KeyCount*(Length of Key + Length of Data) with HashLoadFactor=140..200Pct.
iBBHashSize = udfGetPrimeThisOrNext (Int (@GOLDENRATIO * iKeywordCount)) * iBBHashRecSize ; Try to make the hash more perfect. ; Test.20020823
hBBHash = BinaryAlloc (iBBHashSize)

For i = 1 To iKeywordCount
   sKeywordItem = ItemExtract (i, sKeywordList, @TAB)
   sColorNameItem = StrTrim (IniReadPvt ("KEYWORDS", sKeywordItem, "", sFilenameWilClr))
   If (sColorNameItem == "1") Then sColorNameItem = "Keyword" ; Set standard WIL color=1 to "Keyword" as set in Registry.
   iBBHashOffset = BinaryHashRec (hBBHash, iBBHashRecSize, iBBHashKeyOffset, iBBHashKeySize, StrLower (sKeywordItem))
   BinaryPokeStr (hBBHash, iBBHashOffset + iBBHashColorNameOffset, StrLower (sColorNameItem))
   BinaryPokeStr (hBBHash, iBBHashOffset + iBBHashMixCaseOffset, sKeywordItem)
Next
BinaryWrite (hBBHash, sFilenameBBHash)

GoSub WriteIni

Drop (sFilenameWilClr, sColorNameItem, iBBHashSize, sFilenameBBHash, iBBHashOffset, i)
Drop (iKeywordCount, sKeywordItem, sKeywordList, CurrentDir, sFilenameW2HIni)
Return
;------------------------------------------------------------------------------------------------------------------------------------------
:InitIni
IniWritePvt ("WBT2HTML", "InternalName", "wbt2html.wbt", sFilenameW2HIni)
IniWritePvt ("WBT2HTML", "FileVersion", sProgVersion, sFilenameW2HIni)
IniWritePvt ("WBT2HTML", "FileVersionDate", sProgVersionDate, sFilenameW2HIni)
IniWritePvt ("WBT2HTML", "FileDescription", "WBT to coloured HTML Script Converter", sFilenameW2HIni)
IniWritePvt ("WBT2HTML", "OriginalFilename", "WBT2HTML.WBT", sFilenameW2HIni)
IniWritePvt ("WBT2HTML", "ProductName", sProgProduct, sFilenameW2HIni)
IniWritePvt ("WBT2HTML", "ProductVersion", "1", sFilenameW2HIni)
IniWritePvt ("WBT2HTML", "CompanyName", "Detlev Dalitz", sFilenameW2HIni)
IniWritePvt ("WBT2HTML", "LegalCopyright", sProgCopyright, sFilenameW2HIni)
IniWritePvt ("WBT2HTML", "Comments", "emailto:dd@dalitz-im-netz.de", sFilenameW2HIni)
IniWritePvt ("WBT2HTML", "IniYmdHms", TimeYmdHms (), sFilenameW2HIni)
IniWritePvt ("WIL", "ColorName", sFilenameWilClr, sFilenameW2HIni)
IniWritePvt ("WIL", "ColorYmdHms", "", sFilenameW2HIni)
IniWritePvt ("WIL", "ColorCRC", "0", sFilenameW2HIni)
IniWritePvt ("WIL", "ColorMD5", "", sFilenameW2HIni)
IniWritePvt ("WIL", "HashName", sFilenameBBHash, sFilenameW2HIni)
IniWritePvt ("WIL", "HashYmdHms", "", sFilenameW2HIni)
IniWritePvt ("WIL", "HashCRC", "0", sFilenameW2HIni)
IniWritePvt ("WIL", "HashMD5", "", sFilenameW2HIni)
IniWritePvt ("", "", "", sFilenameW2HIni) ; Flush the buffer to disk.
Return
;------------------------------------------------------------------------------------------------------------------------------------------
:WriteIni
IniWritePvt ("WIL", "ColorName", sFilenameWilClr, sFilenameW2HIni)
IniWritePvt ("WIL", "ColorYmdHms", FileTimeGetEx (sFilenameWilClr, 2), sFilenameW2HIni)
IniWritePvt ("WIL", "ColorCRC", udfFileCrc32 (sFilenameWilClr), sFilenameW2HIni)
IniWritePvt ("WIL", "ColorMD5", udfFileChecksum (sFilenameWilClr, 0), sFilenameW2HIni)
IniWritePvt ("WIL", "HashName", sFilenameBBHash, sFilenameW2HIni)
IniWritePvt ("WIL", "HashYmdHms", FileTimeGetEx (sFilenameBBHash, 2), sFilenameW2HIni)
IniWritePvt ("WIL", "HashCRC", udfFileCrc32 (sFilenameBBHash), sFilenameW2HIni)
IniWritePvt ("WIL", "HashMD5", udfFileChecksum (sFilenameBBHash, 0), sFilenameW2HIni)
IniWritePvt ("", "", "", sFilenameW2HIni) ; Flush the buffer to disk.
Return
;------------------------------------------------------------------------------------------------------------------------------------------
:ReadIni
iBBHashKeyOffset = 0  ; Key lowercase.
iBBHashKeySize = 60 ; Key lowercase.
iBBHashColorNameOffset = 60 ; Color name.
iBBHashColorNameSize = 30 ; Color name.
iBBHashMixCaseOffset = 90 ; Key content in mixed case as stored in WIL.CLR.
iBBHashMixCaseSize = 30 ; Key content in mixed case as stored in WIL.CLR.
iBBHashRecSize = iBBHashKeySize + iBBHashColorNameSize + iBBHashMixCaseSize
iBBHashRecSize = (1 + (iBBHashRecSize / 16)) * 16 ; Align RecordSize to 16 Byte boundary. ; Test.20020823
sFilenameBBHash = IniReadPvt ("WIL", "HashName", "", sFilenameW2HIni)
Return
; iBBHashKeySize upsized from 30 to 60 chars, regardless of WinBatch's limited var size.
; This is done for runtime security reasons and because of OLE-object names, which are 'oversized' sometimes.
;==========================================================================================================================================
:TagQuote
sMsg = "Tagging Quotes ..."
udsDisplayMsg (sMsg)

qlist = """|'|`" ; Three items: doublequote, singlequote, backquote.
sCommentChar = ";"

sQuoteChars = StrReplace (qlist, "|", "")
sScanChars = StrCat (sQuoteChars, sCommentChar)

sTagIdent = "q"
sTagList%sTagIdent% = sTagOn ; Start list with a well known item.

; Allocate a separate work line buffer, 4 KB should be enough, otherwise enlarge it to your needs.
iBBLineSize = 4096
hBBLine = BinaryAlloc (iBBLineSize)

sBBTag = BinaryTagInit (hBB, @LF, @CR)
While 1
   sBBTag = BinaryTagFind (sBBTag)
   If (sBBTag == "") Then Break
   sLine = BinaryTagExtr (sBBTag, 1)
   If (sLine == "") Then Continue

   sScanLine = StrClean (sLine, sScanChars, "", @TRUE, 2)
   If (StrLen (sScanLine) < 2) Then Continue ; Skip line, no complete quoted literal to replace.
   If (StrSub (sScanLine, 1, 1) == sCommentChar) Then Continue ; Skip line, contains comment only.

   sScanLineQuoteChars = StrClean (sQuoteChars, sScanLine, "", @TRUE, 2)
   iQuoteCount = StrLen (sScanLineQuoteChars)
   For iQuote = 1 To iQuoteCount
      sQuote = StrSub (sScanLineQuoteChars, iQuote, 1)
      sBBLineTag%iQuote% = BinaryTagInit (hBBLine, sQuote, sQuote)
   Next
   sScanLineQuoteChars = StrCat (sScanLineQuoteChars, sCommentChar)

   ; Find literals.
   BinaryEodSet (hBBLine, 0)
   BinaryPokeStr (hBBLine, 0, sLine)
   iScan = 1
   While 1
      sScanLine = BinaryPeekStr (hBBLine, 0, BinaryEodGet (hBBLine))
      iScan = StrScan (sScanLine, sScanLineQuoteChars, iScan, @FWDSCAN)
      If !iScan Then Break

      sChar = StrSub (sScanLine, iScan, 1)
      If (sChar == sCommentChar) Then Break

      iQuote = StrIndex (sScanLineQuoteChars, sChar, 1, @FWDSCAN)
      sBBLineTag = sBBLineTag%iQuote%

      sBBLineTag = BinaryTagFind (sBBLineTag)
      If (sBBLineTag == "") Then Break ; If we break here, then there must be a syntax error in input file.

      sLiteral = BinaryTagExtr (sBBLineTag, 1) ; Exclude current Quote Char from colorizing.
      ;;; sLiteral = StrCat(sChar,sLiteral,sChar) ; do not (!) include quote chars for later colorizing !!!

      If UseVerbose
         sMsgUse = StrCat (sMsg, @LF, "BufferUsage BB ", 100 * BinaryEodGet (hBB) / iBBSize, "%%")
         sMsgUse = StrCat (sMsgUse, @LF, "BufferUsage BBLine ", 100 * BinaryEodGet (hBBLine) / iBBLineSize, "%%")
         sMsgUse = StrCat (sMsgUse, @LF, sLiteral)
         udsDisplayMsg (sMsgUse)
      EndIf

      iItemLocate = ItemLocate (sLiteral, sTagList%sTagIdent%, @TAB)
      If !iItemLocate
         sTagList%sTagIdent% = ItemInsert (sLiteral, -1, sTagList%sTagIdent%, @TAB)
         sTag = StrCat (sTagOn, sTagIdent, ItemCount (sTagList%sTagIdent%, @TAB), sTagOff)
      Else
         sTag = StrCat (sTagOn, sTagIdent, iItemLocate, sTagOff)
      EndIf
      sTag = StrCat (sChar, sTag, sChar) ; Exclude current Quote Char from colorizing.
      sBBLineTag = BinaryTagRepl (sBBLineTag, sTag)

      sBBLineTag%iQuote% = sBBLineTag
      iScan = iScan + StrLen (sTag)
   EndWhile

   ; Replace the line.
   sLine = BinaryPeekStr (hBBLine, 0, BinaryEodGet (hBBLine))
   sTag = StrCat (@LF, sLine, @CR)
   sBBTag = BinaryTagRepl (sBBTag, sTag)
EndWhile

BinaryFree (hBBLine)
Drop (hBBLine)

; --- debug ---
; num = udfItemListToFile (sTagList%sTagIdent%, @tab, StrCat(udfGetTempPath(),"wbt2html.sTagList.",sTagIdent,".txt"))

DropWild ("sBBLineTag*")
Drop (iBBLineSize, iItemLocate, iQuote, iQuoteCount, iScan, qlist)
Drop (sBBTag, sChar, sCommentChar, sLine, sLiteral, sMsg, sMsgUse)
Drop (sQuote, sQuoteChars, sScanChars, sScanLine, sScanLineQuoteChars, sTag, sTagIdent)

Return
;==========================================================================================================================================
:TagComment
sMsg = "Tagging Comments ..."
udsDisplayMsg (sMsg)

clist = ";"

sTagIdent = "c"
sTagList%sTagIdent% = sTagOn ; Start list with a well known item.

ccount = ItemCount (clist, ".")
For c = 1 To ccount
   citem = ItemExtract (c, clist, ".")
   sBBTag = BinaryTagInit (hBB, citem, @CR)
   While 1
      sBBTag = BinaryTagFind (sBBTag)
      If (sBBTag == "") Then Break
      cstr = BinaryTagExtr (sBBTag, 1)
      cstr = StrCat (citem, cstr) ; Include leading comment char for later colorizing.

      If UseVerbose
         sMsgUse = StrCat (sMsg, @LF, "BufferUsage ", 100 * BinaryEodGet (hBB) / iBBSize, "%%", @LF, cstr)
         udsDisplayMsg (sMsgUse)
      EndIf

      iItemLocate = ItemLocate (cstr, sTagList%sTagIdent%, @TAB)
      If !iItemLocate
         sTagList%sTagIdent% = ItemInsert (cstr, -1, sTagList%sTagIdent%, @TAB)
         sTag = StrCat (sTagOn, sTagIdent, ItemCount (sTagList%sTagIdent%, @TAB), sTagOff)
      Else
         sTag = StrCat (sTagOn, sTagIdent, iItemLocate, sTagOff)
      EndIf
      sTag = StrCat (sTag, @CR) ; Exclude trailing 'comment char' (@CR) from colorizing.
      sBBTag = BinaryTagRepl (sBBTag, sTag)
   EndWhile
Next

; --- debug ---
; num = udfItemListToFile (sTagList%sTagIdent%, @tab, StrCat(udfGetTempPath(),"wbt2html.sTagList.",sTagIdent,".txt"))

Drop (c, ccount, citem, clist, cstr, iItemLocate, sBBTag, sMsg, sMsgUse, sTag, sTagIdent)

Return
;==========================================================================================================================================
:TagOperatorMod ; This routine needs the round brackets untouched.
sMsg = "Tagging Operator mod ..."
udsDisplayMsg (sMsg)

sTagIdent = "m"
sTagList%sTagIdent% = sTagOn ; Start list with a well known item.


If (BinaryIndexEx (hBB, 0, "mod", @FWDSCAN, @FALSE) < 0) Then Return ; Nothing to do. No "mod" text fragment found.


; Workaround for the Regular Expression '[ 0-9\)](mod)[ 0-9\(\+\-]'
; KEDIT: change r '[ 0-9\)](mod)[ 0-9\(\+\-]'<font color="#rrggbb">&1</font>' * *

; Build a list of all combinations.
sModList = ""
sListL = " 0123456789)"
sListR = " 0123456789(+-"
iMaxL = StrLen (sListL)
iMaxR = StrLen (sListR)
For iL = 1 To iMaxL
   For iR = 1 To iMaxR
      sModList = ItemInsert (StrCat (StrSub (sListL, iL, 1), StrSub (sListR, iR, 1)), -1, sModList, @TAB)
   Next
Next
Drop (iL, iR, iMaxL, iMaxR, sListL, sListR)


iModReplaced = 0
iModCount = ItemCount (sModList, @TAB)
For iMod = 1 To iModCount
   mstr = ItemExtract (iMod, sModList, @TAB)

   If UseVerbose
      mstr = StrCat (StrSub (mstr, 1, 1), "mod", StrSub (mstr, 2, 1))
      sMsgUse = StrCat (sMsg, @LF, "BufferUsage ", 100 * BinaryEodGet (hBB) / iBBSize, "%%", @LF, mstr)
      udsDisplayMsg (sMsgUse)
   EndIf

   sBBTag = BinaryTagInit (hBB, StrCat (StrSub (mstr, 1, 1), "mod"), StrSub (mstr, 2, 1))
   While 1
      sBBTag = BinaryTagFind (sBBTag)
      If (sBBTag == "") Then Break
      If BinaryTagLen (sBBTag, 0) Then Continue ; not a pure "mod", e.g. " (mod)ified "

      mstr = BinaryPeekStr (hBB, BinaryTagIndex (sBBTag, 1), BinaryTagLen (sBBTag, 1))
      sTag = StrCat (sTagOn, sTagIdent, 2, sTagOff)
      sTag = StrReplace (StrLower (mstr), "mod", sTag)
      sBBTag = BinaryTagRepl (sBBTag, sTag)
      iModReplaced = 1
   EndWhile
Next

If iModReplaced Then sTagList%sTagIdent% = ItemInsert ("mod", -1, sTagList%sTagIdent%, @TAB) ; The one and only keyword in this list.

; --- debug ---
; num = udfItemListToFile (sTagList%sTagIdent%, @tab, StrCat(udfGetTempPath(),"wbt2html.sTagList.",sTagIdent,".txt"))
; num = BinaryWrite(hBB,StrCat(udfGetTempPath(),"wbt2html.hBB.",sTagIdent,".bin"))

Drop (iMod, iModCount, iModReplaced, mstr, sBBTag, sModList, sMsg, sMsgUse, sTag, sTagIdent)

Return
;==========================================================================================================================================
:TagOperator
sMsg = "Tagging Operators ..."
udsDisplayMsg (sMsg)

olist = "==.<=.>=.<>.!=.<.>.**.*./.+.-.&&.||.<<.>>.&.|.^.~.!.+.-.=" ; plus ".mod"
; binary(relational,arithmetic,logical),unary(integer logical,integer & float),assignment

sTagIdent = "o"
sTagList%sTagIdent% = sTagOn ; Start list with a well known item.

ocount = ItemCount (olist, ".")
For o = 1 To ocount
   ostr = ItemExtract (o, olist, ".")

   If UseVerbose
      sMsgUse = StrCat (sMsg, @LF, "BufferUsage ", 100 * BinaryEodGet (hBB) / iBBSize, "%%", @LF, ostr)
      udsDisplayMsg (sMsgUse)
   EndIf

   sTag = StrCat (sTagOn, sTagIdent, 1 + ItemCount (sTagList%sTagIdent%, @TAB), sTagOff)
   If BinaryReplace (hBB, ostr, sTag, @TRUE) Then sTagList%sTagIdent% = ItemInsert (ostr, -1, sTagList%sTagIdent%, @TAB)

Next

; --- debug ---
; num = udfItemListToFile (sTagList%sTagIdent%, @tab, StrCat(udfGetTempPath(),"wbt2html.sTagList.",sTagIdent,".txt"))

Drop (o, ocount, olist, ostr, sMsg, sMsgUse, sTag, sTagIdent)

Return
;==========================================================================================================================================
:TagBracket
sMsg = "Tagging Brackets ..."
udsDisplayMsg (sMsg)

blist = "(.).[.].{.}" ; brackets

sTagIdent = "b"
sTagList%sTagIdent% = sTagOn ; Start list with a well known item.

bcount = ItemCount (blist, ".")
For b = 1 To bcount
   bstr = ItemExtract (b, blist, ".")

   If UseVerbose
      sMsgUse = StrCat (sMsg, @LF, "BufferUsage ", 100 * BinaryEodGet (hBB) / iBBSize, "%%", @LF, bstr)
      udsDisplayMsg (sMsgUse)
   EndIf

   sTag = StrCat (sTagOn, sTagIdent, 1 + ItemCount (sTagList%sTagIdent%, @TAB), sTagOff)
   If BinaryReplace (hBB, bstr, sTag, @TRUE) Then sTagList%sTagIdent% = ItemInsert (bstr, -1, sTagList%sTagIdent%, @TAB)

Next

; --- debug ---
; num = udfItemListToFile (sTagList%sTagIdent%, @tab, StrCat(udfGetTempPath(),"wbt2html.sTagList.",sTagIdent,".txt"))

Drop (b, bcount, blist, bstr, sTag, sMsg, sMsgUse, sTagIdent)

Return
;==========================================================================================================================================
:TagSpecial
sMsg = "Tagging Special Chars ..."
udsDisplayMsg (sMsg)

slist = " |,|@|#|::|:" ; Blank,Comma,ASCII-64,ASCII-35,DoubleColon,Colon. (Percent sign too?)

sTagIdent = "s"
sTagList%sTagIdent% = sTagOn ; Start list with a well known item.

scount = ItemCount (slist, "|")
For s = 1 To scount
   sstr = ItemExtract (s, slist, "|")

   If UseVerbose
      sMsgUse = StrCat (sMsg, @LF, "BufferUsage ", 100 * BinaryEodGet (hBB) / iBBSize, "%%", @LF, sstr)
      udsDisplayMsg (sMsgUse)
   EndIf

   sTag = StrCat (sTagOn, sTagIdent, 1 + ItemCount (sTagList%sTagIdent%, @TAB), sTagOff)
   If BinaryReplace (hBB, sstr, sTag, @TRUE) Then sTagList%sTagIdent% = ItemInsert (sstr, -1, sTagList%sTagIdent%, @TAB)

Next

; --- debug ---
; num = udfItemListToFile (sTagList%sTagIdent%, @tab, StrCat(udfGetTempPath(),"wbt2html.sTagList.",sTagIdent,".txt"))

Drop (sMsg, sMsgUse, s, scount, slist, sstr, sTag, sTagIdent)

Return
;==========================================================================================================================================
:TagWordNumber
sMsg = "Tagging Words and Numbers ..."
udsDisplayMsg (sMsg)

sTagIdentWord = "w"
sTagList%sTagIdentWord% = sTagOn ; Start list with a well known item.

sTagIdentNumber = "n"
sTagList%sTagIdentNumber% = sTagOn ; Start list with a well known item.

; "hide" all @crlf
BinaryReplace (hBB, @CRLF, StrCat (sTagOn, @CRLF, sTagOff), @FALSE)

sBBTag = BinaryTagInit (hBB, sTagOff, sTagOn)
While 1
   sBBTag = BinaryTagFind (sBBTag)
   If (sBBTag == "") Then Break
   sWordNumber = BinaryTagExtr (sBBTag, 1)
   If (sWordNumber == "") Then Continue

   If UseVerbose
      sMsgUse = StrCat (sMsg, @LF, "BufferUsage ", 100 * BinaryEodGet (hBB) / iBBSize, "%%", @LF, sWordNumber)
      udsDisplayMsg (sMsgUse)
   EndIf

   If IsNumber (sWordNumber)
      iItemLocate = ItemLocate (sWordNumber, sTagList%sTagIdentNumber%, @TAB)
      If !iItemLocate
         sTagList%sTagIdentNumber% = ItemInsert (sWordNumber, -1, sTagList%sTagIdentNumber%, @TAB)
         iItemLocate = ItemCount (sTagList%sTagIdentNumber%, @TAB)
      EndIf
      sTag = StrCat (sTagOff, sTagOn, sTagIdentNumber, iItemLocate, sTagOff, sTagOn)
   Else
      iItemLocate = ItemLocate (sWordNumber, sTagList%sTagIdentWord%, @TAB)
      If !iItemLocate
         sTagList%sTagIdentWord% = ItemInsert (sWordNumber, -1, sTagList%sTagIdentWord%, @TAB)
         iItemLocate = ItemCount (sTagList%sTagIdentWord%, @TAB)
      EndIf
      sTag = StrCat (sTagOff, sTagOn, sTagIdentWord, iItemLocate, sTagOff, sTagOn)
   EndIf
   sBBTag = BinaryTagRepl (sBBTag, sTag)
EndWhile

; "unhide" all @crlf
BinaryReplace (hBB, StrCat (sTagOn, @CRLF, sTagOff), @CRLF, @FALSE)

; --- debug ---
; num = udfItemListToFile (sTagList%sTagIdentNumber%, @tab, StrCat(udfGetTempPath(),"wbt2html.sTagList.",sTagIdentNumber,".txt"))
; num = udfItemListToFile (sTagList%sTagIdentWord%, @tab, StrCat(udfGetTempPath(),"wbt2html.sTagList.",sTagIdentWord,".txt"))
; num = BinaryWrite(hBB,StrCat(udfGetTempPath(),"wbt2html.hBB.",sTagIdentWord,".bin"))

Drop (iItemLocate, sMsg, sMsgUse, sBBTag, sTagIdentNumber, sTagIdentWord, sWordNumber, sTag)

Return
;==========================================================================================================================================
:EncodeNamedEntities
sMsg = "Encoding HTML Named Entities ..."
udsDisplayMsg (sMsg)

sTagListo = StrReplace (sTagListo, "&", "&#38;")
sTagListo = StrReplace (sTagListo, "<", "&#60;")
sTagListo = StrReplace (sTagListo, ">", "&#62;")

sTagListc = StrReplace (sTagListc, "&", "&#38;")
sTagListc = StrReplace (sTagListc, "<", "&#60;")
sTagListc = StrReplace (sTagListc, ">", "&#62;")

sTagListq = StrReplace (sTagListq, "&", "&#38;")
sTagListq = StrReplace (sTagListq, '"', "&#34;")
sTagListq = StrReplace (sTagListq, "<", "&#60;")
sTagListq = StrReplace (sTagListq, ">", "&#62;")
sTagListq = StrReplace (sTagListq, "{", "&#123;")
sTagListq = StrReplace (sTagListq, "}", "&#125;")

sTagListc = StrReplace (sTagListc, "ä", "&#228;")
sTagListc = StrReplace (sTagListc, "ö", "&#246;")
sTagListc = StrReplace (sTagListc, "ü", "&#252;")
sTagListc = StrReplace (sTagListc, "Ä", "&#196;")
sTagListc = StrReplace (sTagListc, "Ö", "&#214;")
sTagListc = StrReplace (sTagListc, "Ü", "&#220;")
sTagListc = StrReplace (sTagListc, "ß", "&#223;")

sTagListq = StrReplace (sTagListq, "ä", "&#228;")
sTagListq = StrReplace (sTagListq, "ö", "&#246;")
sTagListq = StrReplace (sTagListq, "ü", "&#252;")
sTagListq = StrReplace (sTagListq, "Ä", "&#196;")
sTagListq = StrReplace (sTagListq, "Ö", "&#214;")
sTagListq = StrReplace (sTagListq, "Ü", "&#220;")
sTagListq = StrReplace (sTagListq, "ß", "&#223;")

; For details see Unicode "ISO 10646"
Return
;==========================================================================================================================================
:ColorizeWord

sTagIdent = "w"

If (sTagList%sTagIdent% == sTagOn) ; No words to colorize.
   Drop (sTagList%sTagIdent%)
   Drop (sTagIdent)
   BinaryFree (hBBHash)
   DropWild ("hBBHash*")
   DropWild ("iBBHash*")
   Return
EndIf

iWordCount = ItemCount (sTagList%sTagIdent%, @TAB)
iColorCount = ItemCount (sColorNameList, @TAB)

; fill the lists with well known items
sFillItem = StrCat (sTagOn, @TAB)
iFillCount = (2 * iWordCount) - 1
For iColor = 1 To iColorCount
   sTagList%sTagIdent%%iColor% = StrFill (sFillItem, iFillCount)
Next
Drop (sFillItem, iFillCount)

iColorDefault = ItemLocate ("default text", sColorNameList, @TAB)
For iWord = 2 To iWordCount
   sWord = ItemExtract (iWord, sTagList%sTagIdent%, @TAB)
   iBBHashOffset = BinaryHashRec (hBBHash, iBBHashRecSize, iBBHashKeyOffset, iBBHashKeySize, StrLower (sWord))
   sColorName = BinaryPeekStr (hBBHash, iBBHashOffset + iBBHashColorNameOffset, iBBHashColorNameSize)
   If (sColorName == "")
      BinaryPoke (hBBHash, iBBHashOffset, 0) ; Housekeeping the HashTable.
      iColor = iColorDefault
   Else
      iColor = ItemLocate (sColorName, sColorNameList, @TAB)
      If iColor == 0
         FileAttrSet (sFilenameBBHash, "rash")
         FileDelete (sFilenameBBHash)
         Message ("Error", StrCat ("Color name not found.", @LF, "Maybe hash file is corrupt.", @LF, "Run script again."))
         Exit
      EndIf
      Select UseCase
      Case 4
         sWord = BinaryPeekStr (hBBHash, iBBHashOffset + iBBHashMixCaseOffset, iBBHashMixCaseSize)
         Break
      Case 3
         sWord = StrUpper (sWord)
         Break
      Case 2
         sWord = StrLower (sWord)
         Break
      Case 1
         ; sWord = sWord ; Freestyle, no change.
         Break
      EndSelect
   EndIf
   sTagList%sTagIdent%%iColor% = ItemReplace (sWord, iWord, sTagList%sTagIdent%%iColor%, @TAB)
Next
Drop (sTagList%sTagIdent%, iWordCount, sWord, iWord, sColorName, iBBHashOffset, iColorDefault)

BinaryFree (hBBHash) ; Hashbuffer has done his job.
DropWild ("hBBHash*")
DropWild ("iBBHash*")

For iColor = 1 To iColorCount
   If (StrClean (sTagList%sTagIdent%%iColor%, StrCat (@TAB, sTagOn), "", @TRUE, 1) > "")
      sColorName = ItemExtract (iColor, sColorNameList, @TAB)

      sMsg = StrCat ("Colorizing Words (", sColorName, ") ...")
      GoSub ReplaceColorTag

   EndIf
   Drop (sTagList%sTagIdent%%iColor%)
Next
Drop (iColorCount, sColorName, iColor)

Drop (sTagIdent)
Return
;==========================================================================================================================================
:ColorizeNumber
sTagIdent = "n"
If (sTagList%sTagIdent% <> sTagOn)
   sMsg = "Colorizing Numbers ..."
   sColorName = "Number"
   GoSub ReplaceColorTag
EndIf
Drop (sColorName, sTagList%sTagIdent%, sTagIdent)
Return
;==========================================================================================================================================
:ColorizeSpecial
sTagIdent = "s"
If (sTagList%sTagIdent% <> sTagOn)
   sMsg = "Colorizing Special Chars ..."
   sColorName = "" ; "" or "Special"
   GoSub ReplaceColorTag
EndIf
Drop (sColorName, sTagList%sTagIdent%, sTagIdent)
Return
;==========================================================================================================================================
:ColorizeBracket
sTagIdent = "b"
If (sTagList%sTagIdent% <> sTagOn)
   sMsg = "Colorizing Brackets ..."
   sColorName = "" ; "" or "Bracket"
   GoSub ReplaceColorTag
EndIf
Drop (sColorName, sTagList%sTagIdent%, sTagIdent)
Return
;==========================================================================================================================================
:ColorizeOperator
sTagIdent = "o"
If (sTagList%sTagIdent% <> sTagOn)
   sMsg = "Colorizing Operators ..."
   sColorName = "Operator"
   GoSub ReplaceColorTag
EndIf
Drop (sColorName, sTagList%sTagIdent%, sTagIdent)
Return
;==========================================================================================================================================
:ColorizeOperatorMod
sTagIdent = "m"
If (sTagList%sTagIdent% <> sTagOn)
   sMsg = "Colorizing Operator mod ..."
   sColorName = "Operator"
   GoSub ReplaceColorTag
EndIf
Drop (sColorName, sTagList%sTagIdent%, sTagIdent)
Return
;==========================================================================================================================================
:ColorizeComment
sTagIdent = "c"
If (sTagList%sTagIdent% <> sTagOn)
   sMsg = "Colorizing Comments ..."
   sColorName = "Comment"
   GoSub ReplaceColorTag
EndIf
Drop (sColorName, sTagList%sTagIdent%, sTagIdent)
Return
;==========================================================================================================================================
:ColorizeQuote
sTagIdent = "q"
If (sTagList%sTagIdent% <> sTagOn)
   sMsg = "Colorizing Quotes ..."
   sColorName = "Quote"
   GoSub ReplaceColorTag
EndIf
Drop (sColorName, sTagList%sTagIdent%, sTagIdent)
Return
;==========================================================================================================================================
:ReplaceColorTag ; needs a sTagListx

udsDisplayMsg (sMsg)

If (sTagIdent <> "w") Then iColor = ""
iTagCount = ItemCount (sTagList%sTagIdent%%iColor%, @TAB)

For iTag = iTagCount To 1 By -1

   If UseVerbose
      iPercent = 100 - (100 * iTag / iTagCount)
      If !(iPercent mod 10)
         udsDisplayMsg (StrCat (sMsg, @LF, "Tags done ", iPercent, "%%", @LF, "BufferUsage ", 100 * BinaryEodGet (hBB) / iBBSize, "%%"))
      EndIf
   EndIf

   If UseAnimation
      iPercent = 100 - (100 * iTag / iTagCount)
      iBBEod = BinaryEodGet (hBB) - 1
      iBBEodFactor = iBBEod / iTagCount
      iBBBottom = iBBEodFactor * (iTag - 1)
      iBBTop = Min (iBBEod - iBBBottom, iBBBottom + iBBEodFactor)
      ; Important Note: BoxText causes an error 12000 abort if this script has been called via WSPOPUP.MNU !
      BoxText (StrCat (sMsg, @LF, "Tags done ", iPercent, "%%", @LF, BinaryPeekStr (hBB, iBBBottom, iBBTop)))
   EndIf

   sTag = ItemExtract (iTag, sTagList%sTagIdent%%iColor%, @TAB)

   ; Skip placeholder.
   If (sTag == sTagOn) Then Continue

   ; Empty sTag requires no colorizing.
   If (sTag == "")
      BinaryReplace (hBB, StrCat (sTagOn, sTagIdent, iTag, sTagOff), sTag, @FALSE)
      Continue
   EndIf

   ; Create the font color html tag.
   sColorValue = ItemExtract (ItemLocate (StrLower (sColorName), sColorNameList, @TAB), sColorValueList, @TAB)
   If (sColorValue > "")
      sTag = StrReplace (sFontTagDefault, "{{txt}}", sTag)
      sTag = StrReplace (sTag, "{{col}}", sColorValue)
   EndIf
   BinaryReplace (hBB, StrCat (sTagOn, sTagIdent, iTag, sTagOff), sTag, @FALSE)
Next

Drop (iBBBottom, iBBTop, iBBEod, iBBEodFactor, sTag, iTag, iPercent)
Drop (sColorValue, iTagCount)
Drop (sTagList%sTagIdent%%iColor%)
Return
;==========================================================================================================================================
:OpenReadSourceFile
sMsg = "Reading source file "
sMsg = StrCat (sMsg, @LF, sFilenameSource)
udsDisplayMsg (sMsg)

iFileSize = FileSizeEx (sFilenameSource)
Terminate (!iFileSize, "Error", "Sourcefile has FileSize=0")

Exclusive (@OFF)
If (iFileSize > 16384) Then Exclusive (@ON)      ; Speed up performance on large files.
iBBSize = iFileSize * 16                      ; Or more ? (changing plain text to html lets grow the file sometimes enormously).
iBBSize = Max (16384, iBBSize)                  ; Minimum 16KB Buffer.
hBB = BinaryAlloc (iBBSize)

BinaryPokeStr (hBB, 0, @LF)                      ; A little helper @LF.
BinaryPokeStr (hBB, 1, @CRLF)                    ; A little helper @CRLF.
BinaryReadEx (hBB, 3, sFilenameSource, 0, iFileSize)
BinaryPokeStr (hBB, BinaryEodGet (hBB), @CRLF)    ; A little helper @CRLF.
BinaryPokeStr (hBB, BinaryEodGet (hBB), @CR)      ; A little helper @CR.

BinaryReplace (hBB, @TAB, StrFill (" ", UseTabReplaceSize), @FALSE) ; Clean Tabs.

Drop (iFileSize)
Return
;==========================================================================================================================================
:CalculateDelimiters
sMsg = "Calculating delimiters ... be patient ... on file"
sMsg = StrCat (sMsg, @LF, sFilenameSource)
udsDisplayMsg (sMsg)

; Create a chartable ...
sTag = ""
For iTag = 1 To 31
   sTag = StrCat (sTag, Num2Char (iTag))
Next
For iTag = 129 To 255
   sTag = StrCat (sTag, Num2Char (iTag))
Next
sTag = StrReplace (sTag, @TAB, "")
sTag = StrReplace (sTag, @CR, "")
sTag = StrReplace (sTag, @LF, "")
sTag = StrClean (sTag, BinaryPeekStr (hBB, 0, BinaryEodGet (hBB) - 1), "", @FALSE, 1)
; ... and have used chars deleted.
Terminate ((StrLen (sTag) < 2), StrCat (sLogo, "Error"), "This special WBT sourcefile cannot be converted into HTML ('tag chars not available').")
sTagOn = StrSub (sTag, 1, 1)
sTagOff = StrSub (sTag, 2, 1)
Drop (iTag, sTag)
Return
;==========================================================================================================================================
:WriteCloseTargetFile
sMsg = "Writing target file "
sMsg = StrCat (sMsg, @LF, sFilenameTarget)
udsDisplayMsg (sMsg)

; --- Create HTML page structure with Header and Footer.

; Create comments.
; sHtmTagCommentOpen = '<!-- ' ; The standard HTML comment.
sHtmTagCommentOpen = '<! '   ; Tweaked for better use in WinBatch Forum.
sHtmTagCommentClose = ' -->'

sHtmCommentLogo = StrCat ("[", TimeYmdHms (), "]")
sHtmCommentLogo = StrCat (sHtmCommentLogo, " colorized HTML by ", sProgProduct, " v", sProgVersion, " ", sProgCopyright)
sHtmCommentLogo = StrCat (sHtmTagCommentOpen, sHtmCommentLogo, sHtmTagCommentClose)

sHtmCommentColorList = ""
iCount = ItemCount (sColorNameList, @TAB)
For i = 1 To iCount
   sColorNameItem = ItemExtract (i, sColorNameList, @TAB)
   sColorValueItem = ItemExtract (i, sColorValueList, @TAB)
   sHtmCommentColorList = ItemInsert (StrCat ('"', sColorNameItem, '"="', sColorValueItem, '"'), -1, sHtmCommentColorList, ";")
Next
Drop (i, iCount)
sHtmCommentColorList = StrCat (sHtmTagCommentOpen, sHtmCommentColorList, sHtmTagCommentClose)


; Set style for fonts. Read font attributes for WIL files from WinBatch Studio Registry.
sFontFamily = "Courier New" ; Default.
sFontSize = "9"           ; Default.
sFontWeight = "400"         ; Default.
sFontStyle = "0"           ; Default.

sRegKeySub = "Software\Wilson WindowWare\WinBatch Studio\Settings\File types\WIL Files"
If RegExistKey (@REGCURRENT, sRegKeySub)
   hRegKey = RegOpenKeyEx (@REGCURRENT, sRegKeySub, 1, "", "")
   ; Mode=1=KEY_QUERY_VALUE=Permission to query subkey data ; We only need read access.
   sRegKeySub = "[Font name]"
   If RegExistValue (hRegKey, sRegKeySub) Then sFontFamily = RegQueryValue (hRegKey, sRegKeySub)
   sRegKeySub = "[Font size]"
   If RegExistValue (hRegKey, sRegKeySub) Then sFontSize = RegQueryValue (hRegKey, sRegKeySub)
   sRegKeySub = "[Font weight]"
   If RegExistValue (hRegKey, sRegKeySub) Then sFontWeight = RegQueryValue (hRegKey, sRegKeySub)
   sRegKeySub = "[Font Italic]"
   If RegExistValue (hRegKey, sRegKeySub) Then sFontStyle = RegQueryValue (hRegKey, sRegKeySub)
   RegCloseKey (hRegKey)
   Drop (hRegKey, sRegKeySub)
EndIf

sFontStyle = ItemExtract (1 + sFontStyle, "normal,italic", ",") ; Translate number to string.

sStyleFont = "font-family:'{{sFontFamily}}'; font-size:{{sFontSize}}pt; font-weight:{{sFontWeight}}; font-style:{{sFontStyle}}; "
sStyleFont = StrReplace (sStyleFont, "{{sFontFamily}}", sFontFamily)
sStyleFont = StrReplace (sStyleFont, "{{sFontSize}}", sFontSize)
sStyleFont = StrReplace (sStyleFont, "{{sFontWeight}}", sFontWeight)
sStyleFont = StrReplace (sStyleFont, "{{sFontStyle}}", sFontStyle)
DropWild ("sFont*")


; Set style for Foreground, Background, Border, Image.
sColorValueFg = StrLower (ItemExtract (ItemLocate (StrLower ("Default Text"), sColorNameList, @TAB), sColorValueList, @TAB))
sColorValueBg = StrLower (ItemExtract (ItemLocate (StrLower ("Background"), sColorNameList, @TAB), sColorValueList, @TAB))
If UseRGB
   sColorValueFg = StrCat ('rgb(', sColorValueFg, ')')
   sColorValueBg = StrCat ('rgb(', sColorValueBg, ')')
EndIf

sStyleColorFg = StrCat ('color:', sColorValueFg, '; ')
sStyleColorBg = StrCat ("background-color:", sColorValueBg, "; ")

sStyleBorder = "border:1pt solid #dddddd; padding:3pt; width:100%%; "

sStyleImageBg = "background-image:url(../images/gif/grid.gif); " ; My background image.
; sStyleImageBg = "" ; Activate this line if no background image to use.


; Create PRE tag.
sHtmTagPre = StrCat ('<pre style="', sStyleImageBg, sStyleColorBg, sStyleBorder, sStyleFont, sStyleColorFg, '"')
sHtmTagPre = StrCat (sHtmTagPre, ' title="colorized by WBT2HTML">')


; Create Header, Footer.
sHtmHeader = StrCat ('<html>', @CRLF, '<body>', @CRLF, sHtmCommentLogo, @CRLF, sHtmCommentColorList, @CRLF, sHtmTagPre, @CRLF)
sHtmFooter = StrCat ('</pre>', @CRLF, '</body>', @CRLF, '</html>', @CRLF)


; Write the HTML file.
BinaryEodSet (hBB, BinaryEodGet (hBB) - 1) ; Cut little helper @CR.
BinaryEodSet (hBB, BinaryEodGet (hBB) - 2) ; Cut little helper @CRLF.
If (BinaryPeekStr (hBB, BinaryEodGet (hBB) - 2, 2) <> @CRLF) Then BinaryPokeStr (hBB, BinaryEodGet (hBB), @CRLF) ; Add @CRLF for sure.
hBBHelp = BinaryAlloc (1024)
BinaryWriteEx (hBBHelp, 0, sFilenameTarget, 0, -1) ; Set new eof marker.
BinaryPokeStr (hBBHelp, 0, sHtmHeader)
BinaryWriteEx (hBBHelp, 0, sFilenameTarget, 0, BinaryEodGet (hBBHelp)) ; Write Header.
BinaryWriteEx (hBB, 3, sFilenameTarget, FileSize (sFilenameTarget), BinaryEodGet (hBB) - 3) ; Write the main buffer, ommit helper @CRLF@CR.
BinaryEodSet (hBBHelp, 0)
BinaryPokeStr (hBBHelp, 0, sHtmFooter)
BinaryWriteEx (hBBHelp, 0, sFilenameTarget, FileSize (sFilenameTarget), BinaryEodGet (hBBHelp)) ; Write Footer.

; Close Buffers.
BinaryFree (hBBHelp)
BinaryFree (hBB)
Drop (hBB, hBBHelp)


sMsg = "Ready."
udsDisplayMsg (sMsg)

TimeDelay (1)
If (RtStatus () <> 10) Then BoxShut ()

DropWild ("sStyle*")
DropWild ("sColor*")
DropWild ("sHtm*")
DropWild ("Use*")

Return
;==========================================================================================================================================
:ProgInit
sProgProduct = "WBT2HTML"
sProgVersion = "1.25"
sProgVersionDate = "20020825"
sProgCopyright = StrCat ("(c)20010729-", sProgVersionDate, " Detlev Dalitz")

sLogo = StrCat (sProgProduct, ": ")
sLogoLong = StrCat (sProgProduct, " v", sProgVersion, " ", sProgVersionDate, "      ", sProgCopyright")

If (RtStatus () <> 10) Then BoxOpen (sLogoLong, "Be patient")
sMsg = "Initiating ..."
udsDisplayMsg (sMsg)

If UseRGB
   sFontTagDefault = '<font color="rgb({{col}})">{{txt}}</font>'
Else
   sFontTagDefault = '<font color="{{col}}">{{txt}}</font>'
EndIf

If (UseAnimation && (RtStatus () == 10)) Then BoxOpen (sLogoLong, "Be patient, 'animated run' will follow after tagging ...")

Return
;==========================================================================================================================================
:GetParams
Drop (sFilenameSource, sFilenameTarget)
If !ItemLocate (StrLower (FileExtension (Param1)), "wbt|web", "|")
   Message ("Error", "WBT2HTM.WBT needs a *.WBT or *.WEB file as input.")
   iParamError = 1
Else
   If IsDefined (Param1) Then sFilenameSource = Param1
   If IsDefined (Param2)
      sFilenameTarget = StrCat (FilePath (Param2), FileRoot (Param2), ".htm") ; Force extension.
   Else
      sFilenameTarget = StrCat (FilePath (Param1), FileRoot (Param1), ".", FileExtension (Param1), ".htm") ; Add extension.
   EndIf
   iParamError = 0
EndIf
Return
;==========================================================================================================================================
:AskParams
AFN_title = "WBT2HTML: Select WBT or WEB File to convert to HTM"
AFN_folder = "W:\WINBATCH\2001\"  ; Define your standard folder here.
AFN_filetypes = "WIL Files|*.wbt;*.web|HTML Files|*.htm;*.html|All Files|*.*|"
AFN_default = "*.wbt;*.web"
AFN_flag = 1  ; Open single file.
While 1
   sFilenameSource = AskFilename (AFN_title, AFN_folder, AFN_filetypes, AFN_default, AFN_flag)
   AFN_folder = FilePath (sFilenameSource)
   If !Call (IntControl (1004, 0, 0, 0, 0), '"%sFilenameSource%"') ; Call this script again with quoted filename.
      sFilenameHtm = StrCat (sFilenameSource, ".htm")
      If (FileExist (sFilenameHtm)) Then RunZoom ("iexplore.exe", sFilenameHtm)
   EndIf
EndWhile
Exit
; todo notes:
; The starting AFN_folder should be added to section UserConfigurableInit, may add to INI file.
; May remember the last working folder in INI file.
; sHtmFile should be identical to sFilenameTarget (may make the same variable)
;==========================================================================================================================================



;==========================================================================================================================================
:UserConfigurableInit ;############ user configurable area begin ###############
;------------------------------------------------------------------------------------------------------------------------------------------
;UseCase=1     ; 1=freestyle
;UseCase=2     ; 2=lowercase
;UseCase=3     ; 3=uppercase
UseCase = 4     ; 4=standardcase as defined in WIL.CLR resp. as stored in HashTable

;UseRGB=@TRUE  ; activate this line for '<font color="rgb(rrr,ggg,bbb)"></font>'
UseRGB = @FALSE  ; activate this line for '<font color="#rrggbb"></font>'

;UseVerbose=@TRUE ; more screen Messages
UseVerbose = @FALSE ; less screen Messages

;UseAnimation=@TRUE ; If you have time to waste and need some animation ...
UseAnimation = @FALSE

;UseAutoDelimiter=@TRUE
UseAutoDelimiter = @FALSE
;If you set UseAutoDelimiter=@FALSE then sTagOn and sTagOff must be defined manually!!!
;Otherwise unpredictable results will occur!
sTagOn = Num2Char (215)
sTagOff = Num2Char (208)

UseTabReplaceSize = 3 ; If there exist tabs in the source file then replace it with blanks
;------------------------------------------------------------------------------------------------------------------------------------------
Return ;########################### user configurable area end #################
;==========================================================================================================================================



;==========================================================================================================================================
; syntax 1 (call by another program or start on the commandline without Parameters):
; WBT2HTML.WBT
; opens an AskFilename dialog
;
; syntax2 (call or start with Parameters):
; WBT2HTML.WBT sFilenameSource [sFilenameTarget]
;
; If sFilenameTarget is omitted then sFilenameSource will be used
; with added extension ".htm"
;
; example1:
; WBT2HTML.WBT mybest.wbt
; will create  mybest.wbt.htm
;
; example2:
; WBT2HTML.WBT mybest.wbt mybad.htm
; will create  mybad.htm
;
; Good luck! Viel Spass! And happy converting ...
;==========================================================================================================================================


;==========================================================================================================================================
; This was the initial idea and starting point of this program:
; -- mit  Quotes, KEDIT change r §((("{[~"]@}")|('{[~']@}')|(`{[~`]@}`)))\c§<_font color="#aaaaaa">&1&2&3<_/font>§ * *             --
; -- ohne Quotes, KEDIT change r §((({"}{[~"]@}{"})|({'}{[~']@}{'})|({`}{[~`]@}{`})))\c§<_font color="#aaaaaa">&2&5&8<_/font>§ * * --
;==========================================================================================================================================

;==========================================================================================================================================
; Note:
; - wbt2html creates an ini file "wbt2html.ini" in winbatch system folder
; - creates a hash file "WIL.HSH" in temp folder
; - needs WIL's serial extender "wwser34i.dll"
; - html output is placed in source folder.
;==========================================================================================================================================

;==========================================================================================================================================
; Note:
; Although it is possible to call the WBT2HTML.wbt script via WSPOPUP.MNU entry,
; the script would not run successfully if UseAnimation is set @TRUE.
; The 'Animation' uses the normal BoxText statement, but this is
; NOT allowed to be used from within the WSPOPUP.MNU environment.
; The script will abort with error number 12000.
;
; Workaround:
; Choice 1. Always do set 'UseAnimation=@FALSE' if calling the script via WSPOPUP.MNU.
; Choice 2. 'Run' the WBT2HTML.WBT via WSPOPUP.MNU entry.
; Choice 3. 'Run' or 'Runwait' the WBT2HTML.WBT via a helper wbt script which is called from WSPOPUP.MNU entry.
;            Choice 3 allows to select text passages from current edit text and send it via ClipGet to WBT2HMTL.WBT.
;            Those caller script can be something like the following script 'WBStudioToWBT2HTML.wbt'.
;==========================================================================================================================================


;==========================================================================================================================================
; Known Issues:
; None.
;==========================================================================================================================================



;==========================================================================================================================================
; WBStudioToWBT2HTML.wbt
;==========================================================================================================================================
; Caller utility for WBT2HTML.WBT.
; This script should only be called from a WSPOPUP.MNU menu entry from within WinBatch Studio.
; It directs the selected edit text via Clipboard and external tempfile to the WBT2HTML.WBT.
; After returning from WBT2HTML transformation it puts the html output data to Clipboard for following pasting elsewhere.
;------------------------------------------------------------------------------------------------------------------------------------------
; Call this cript from WSPOPUP.MNU, for example:
;
; WBT2HTML via ClipBoard
;    call("W:\WINBATCH\Scripts\WBStudioToWBT2HTML.wbt","")
;
;------------------------------------------------------------------------------------------------------------------------------------------
; Detlev Dalitz.20011113.20020808
;------------------------------------------------------------------------------------------------------------------------------------------

InStudio = (RtStatus () == 10)
If !InStudio Then Exit
If InStudio
   If !wGetSelState () Then wSelectAll ()
   wCopy ()
EndIf
wClearSel ()

iBBSize = BinaryClipGet (0, 1)
If !iBBSize Then Return ; nothing to do

hBB = BinaryAlloc (iBBSize)
num = BinaryClipGet (hBB, 1)
Display (2, "WBT2HTML", "Selected Text copied to ClipBoard, %num% Byte to format ...")

tempfile = FileCreateTemp ("TMP")
tempfile = FileLocate (tempfile)
wbtfile = StrCat (tempfile, ".wbt")
htmfile = StrCat (tempfile, ".htm")
FileRename (tempfile, wbtfile)

num = BinaryWrite (hBB, wbtfile)
BinaryFree (hBB)

WILBatchfile = '"W:\WINBATCH\Scripts\WBT2HTML.WBT"' ; Change the path to your needs.
RunWait (StrCat (DirHome (), "WinBatch.exe"), StrCat (WILBatchfile, " ", wbtfile, " ", htmfile))

If FileExist (htmfile)
   iBBSize = FileSize (htmfile)
   hBB = BinaryAlloc (iBBSize)
   num = BinaryRead (hBB, htmfile)
   num = BinaryClipPut (hBB, 1)
   num = BinaryClipGet (0, 1)
   BinaryFree (hBB)
   Display (2, "WBT2HTML", "HTML copied to ClipBoard, %num% Byte to paste ...")
EndIf

:CANCEL
FileDelete (htmfile)
FileDelete (wbtfile)

Drop (hBB, iBBSize, htmfile, InStudio, num, tempfile, wbtfile, WILBatchfile)

Exit
;==========================================================================================================================================