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

FUNCTION ReverseStr(BYREF s AS STRING) AS STRING
    LOCAL i AS LONG, 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(BYREF s AS STRING, ch AS STRING) AS LONG
    LOCAL i AS LONG, cnt AS LONG
    i = 1
    WHILE i <= LEN(s)
        IF MID$(s, i, 1) = ch THEN cnt = cnt + 1
        i = i + 1
    WEND
    FUNCTION = cnt
END FUNCTION

FUNCTION ToUpper(BYREF s AS STRING) AS STRING
    LOCAL i AS LONG, c AS LONG, 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 IsPalindromeStr(BYREF s AS STRING) AS LONG
    LOCAL i AS LONG, j AS LONG
    i = 1: j = LEN(s)
    WHILE i < j
        IF MID$(s, i, 1) <> MID$(s, j, 1) THEN FUNCTION = 0: EXIT FUNCTION
        i = i + 1: j = j - 1
    WEND
    FUNCTION = 1
END FUNCTION

FUNCTION WordCount(BYREF s AS STRING) AS LONG
    LOCAL i AS LONG, cnt AS LONG, inWord AS LONG
    i = 1: cnt = 0: inWord = 0
    WHILE i <= LEN(s)
        IF MID$(s, i, 1) <> " " THEN
            IF inWord = 0 THEN cnt = cnt + 1: inWord = 1
        ELSE
            inWord = 0
        END IF
        i = i + 1
    WEND
    FUNCTION = cnt
END FUNCTION

FUNCTION GCD(a AS LONG, b AS LONG) AS LONG
    LOCAL tmp AS LONG
    WHILE b > 0
        tmp = b
        b = a MOD b
        a = tmp
    WEND
    FUNCTION = a
END FUNCTION

FUNCTION PBMAIN() AS LONG
    LOCAL s AS STRING

    PRINT "B64 String Processing Demo"
    PRINT "========================="
    PRINT ""

    s = "Hello from PBXB64!"

    PRINT "Original: "; s
    PRINT "Reversed: "; ReverseStr(s)
    PRINT "'l' count: "; CountChar(s, "l")
    PRINT "'o' count: "; CountChar(s, "o")
    PRINT "Uppercase: "; ToUpper(s)

    PRINT ""
    PRINT "Palindrome checks:"
    PRINT "  'racecar': "; IsPalindromeStr("racecar")
    PRINT "  'hello': "; IsPalindromeStr("hello")
    PRINT "  'madam': "; IsPalindromeStr("madam")

    PRINT ""
    s = "the quick brown fox jumps over the lazy dog"
    PRINT "Word count: '"; s; "' = "; WordCount(s)

    PRINT ""
    PRINT "Math: GCD(48, 18) = "; GCD(48, 18)
    PRINT "      GCD(100, 35) = "; GCD(100, 35)

    PRINT ""
    PRINT "All string processing tests passed."

    FUNCTION = 0
END FUNCTION
