' B64 String Processing — string manipulation functions
#COMPILE EXE
#DIM ALL

FUNCTION ReverseStr(BYVAL s AS STRING) AS STRING
    LOCAL i AS LONG
    LOCAL r AS STRING
    r = ""
    i = LEN(s)
    WHILE i >= 1
        r = r + MID$(s, i, 1)
        i = i - 1
    WEND
    FUNCTION = r
END FUNCTION

FUNCTION CountChar(BYVAL s AS STRING, BYVAL ch AS STRING) AS LONG
    LOCAL i AS LONG
    LOCAL cnt AS LONG
    i = 1
    cnt = 0
    WHILE i <= LEN(s)
        IF MID$(s, i, 1) = ch THEN cnt = cnt + 1
        i = i + 1
    WEND
    FUNCTION = cnt
END FUNCTION

FUNCTION ToUpper(BYVAL s AS STRING) AS STRING
    LOCAL i AS LONG
    LOCAL c AS LONG
    LOCAL r AS STRING
    i = 1
    WHILE i <= LEN(s)
        c = ASC(MID$(s, i, 1))
        IF c >= 97 AND c <= 122 THEN c = c - 32
        r = r + CHR$(c)
        i = i + 1
    WEND
    FUNCTION = r
END FUNCTION

FUNCTION ToLower(BYVAL s AS STRING) AS STRING
    LOCAL i AS LONG
    LOCAL c AS LONG
    LOCAL r AS STRING
    i = 1
    WHILE i <= LEN(s)
        c = ASC(MID$(s, i, 1))
        IF c >= 65 AND c <= 90 THEN c = c + 32
        r = r + CHR$(c)
        i = i + 1
    WEND
    FUNCTION = r
END FUNCTION

FUNCTION IsPalindrome(BYVAL s AS STRING) AS LONG
    LOCAL i AS LONG
    LOCAL n AS LONG
    n = LEN(s)
    FOR i = 1 TO n / 2
        IF MID$(s, i, 1) <> MID$(s, n - i + 1, 1) THEN
            FUNCTION = 0
            EXIT FUNCTION
        END IF
    NEXT i
    FUNCTION = 1
END FUNCTION

FUNCTION CountWords(BYVAL s AS STRING) AS LONG
    LOCAL i AS LONG
    LOCAL cnt AS LONG
    LOCAL inWord AS LONG
    cnt = 0
    inWord = 0
    FOR i = 1 TO LEN(s)
        IF MID$(s, i, 1) <> " " THEN
            IF inWord = 0 THEN
                cnt = cnt + 1
                inWord = 1
            END IF
        ELSE
            inWord = 0
        END IF
    NEXT i
    FUNCTION = cnt
END FUNCTION

FUNCTION PBMAIN() AS LONG
    LOCAL s AS STRING

    PRINT "B64 String Processing Demo"
    PRINT ""

    s = "Hello World"
    PRINT "Original: '" + s + "'"
    PRINT "Reversed: '" + ReverseStr(s) + "'"
    PRINT "UPPERCASE: '" + ToUpper(s) + "'"
    PRINT "lowercase: '" + ToLower(s) + "'"
    PRINT "Is 'racecar' palindrome? "
    IF IsPalindrome("racecar") THEN PRINT "Yes" ELSE PRINT "No"
    PRINT "Word count: " + STR$(CountWords(s))

    s = "Hello World"
    PRINT "Count of 'l': " + STR$(CountChar(s, "l"))
    PRINT "Count of 'o': " + STR$(CountChar(s, "o"))

    FUNCTION = 0
END FUNCTION
