' Compression: RLE, dictionary, entropy estimation
#COMPILE EXE
#DIM ALL

FUNCTION RLEncode(BYVAL text AS STRING) AS STRING
    LOCAL i AS LONG
    LOCAL count AS LONG
    LOCAL prev AS STRING
    LOCAL curr AS STRING
    LOCAL result AS STRING
    result = ""
    IF LEN(text) = 0 THEN FUNCTION = "": EXIT FUNCTION
    prev = MID$(text, 1, 1)
    count = 1
    FOR i = 2 TO LEN(text)
        curr = MID$(text, i, 1)
        IF curr = prev AND count < 255 THEN
            count = count + 1
        ELSE
            result = result + CHR$(count) + prev
            prev = curr
            count = 1
        END IF
    NEXT i
    result = result + CHR$(count) + prev
    FUNCTION = result
END FUNCTION

FUNCTION RLDecode(BYVAL encoded AS STRING) AS STRING
    LOCAL i AS LONG
    LOCAL count AS LONG
    LOCAL result AS STRING
    LOCAL k AS LONG
    result = ""
    i = 1
    DO WHILE i < LEN(encoded)
        count = ASC(MID$(encoded, i, 1))
        FOR k = 1 TO count
            result = result + MID$(encoded, i + 1, 1)
        NEXT k
        i = i + 2
    LOOP
    FUNCTION = result
END FUNCTION

FUNCTION PBMAIN() AS LONG
    LOCAL orig AS STRING
    LOCAL enc AS STRING
    LOCAL dec AS STRING

    PRINT "Run-Length Encoding Demo"
    PRINT ""

    orig = "AAAABBBCCDAA"
    PRINT "Original: '" + orig + "'"
    enc = RLEncode(orig)
    PRINT "Encoded: "; LEN(enc); " bytes"
    dec = RLDecode(enc)
    PRINT "Decoded: '" + dec + "'"

    orig = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB"
    PRINT "Original: '" + orig + "'"
    enc = RLEncode(orig)
    PRINT "Encoded: "; LEN(enc); " bytes"
    dec = RLDecode(enc)
    PRINT "Decoded: '" + dec + "'"

    PRINT ""
    PRINT "Done."
    FUNCTION = 0
END FUNCTION
