' Huffman Compression — character frequency and code table
#COMPILE EXE
#DIM ALL

FUNCTION PBMAIN() AS LONG
    LOCAL chars(25) AS STRING
    LOCAL freq(25) AS LONG
    LOCAL code(25) AS STRING
    LOCAL i AS LONG
LOCAL total AS LONG
    LOCAL c AS STRING
    LOCAL s AS STRING

    chars(0) = "E": freq(0) = 12: code(0) = "01"
    chars(1) = "T": freq(1) = 9: code(1) = "10"
    chars(2) = "A": freq(2) = 8: code(2) = "001"
    chars(3) = "O": freq(3) = 7: code(3) = "110"
    chars(4) = "I": freq(4) = 7: code(4) = "000"
    chars(5) = "N": freq(5) = 6: code(5) = "1110"
    chars(6) = "S": freq(6) = 6: code(6) = "1111"
    chars(7) = "H": freq(7) = 5: code(7) = "0100"
    chars(8) = "R": freq(8) = 5: code(8) = "0101"
    chars(9) = "D": freq(9) = 4: code(9) = "0110"

    chars(10) = "L": freq(10) = 4: code(10) = "0111"
    chars(11) = "C": freq(11) = 3: code(11) = "1000"
    chars(12) = "U": freq(12) = 3: code(12) = "1001"
    chars(13) = "M": freq(13) = 3: code(13) = "1010"
    chars(14) = "W": freq(14) = 2: code(14) = "10110"
    chars(15) = "F": freq(15) = 2: code(15) = "10111"
    chars(16) = "G": freq(16) = 2: code(16) = "11000"
    chars(17) = "Y": freq(17) = 2: code(17) = "11001"
    chars(18) = "P": freq(18) = 2: code(18) = "11010"
    chars(19) = "B": freq(19) = 1: code(19) = "110110"

    chars(20) = "V": freq(20) = 1: code(20) = "110111"
    chars(21) = "K": freq(21) = 1: code(21) = "111000"
    chars(22) = "X": freq(22) = 1: code(22) = "111001"
    chars(23) = "J": freq(23) = 1: code(23) = "111010"
    chars(24) = "Q": freq(24) = 1: code(24) = "111011"
    chars(25) = "Z": freq(25) = 1: code(25) = "111100"

    PRINT "Huffman Compression Demo"
    PRINT "======================="
    PRINT ""

    PRINT "Character frequency table:"
    PRINT "Char  Freq  Code"
    PRINT "----------------"
    total = 0
    i = 0
    WHILE i <= 25
        PRINT "  "; chars(i); "    "; freq(i); "    "; code(i)
        total = total + freq(i)
        i = i + 1
    WEND
    PRINT "Total: "; total
    PRINT ""

    s = "HELLO WORLD"
    PRINT "Original: "; s
    PRINT "Encoded:"
    i = 1
    WHILE i <= LEN(s)
        c = MID$(s, i, 1)
        IF c = "E" THEN PRINT "01";
        IF c = "H" THEN PRINT "0100";
        IF c = "L" THEN PRINT "0111";
        IF c = "O" THEN PRINT "110";
        IF c = "W" THEN PRINT "10110";
        IF c = "R" THEN PRINT "0101";
        IF c = "D" THEN PRINT "0110";
        i = i + 1
    WEND
    PRINT ""
    PRINT ""
    PRINT "ASCII bits: "; 11 * 8
    PRINT "Huffman encoding saves space for frequent chars."

    FUNCTION = 0
END FUNCTION
