#COMPILE EXE
#DIM ALL

FUNCTION PBMAIN() AS LONG
    LOCAL bin_val AS LONG
    LOCAL gray_val AS LONG
    LOCAL decoded_val AS LONG
    LOCAL i AS LONG
    LOCAL temp_val AS LONG
    LOCAL temp_str AS STRING

    PRINT "Gray Code Encoding/Decoding"
    PRINT "==========================="
    PRINT ""
    PRINT "Binary -> Gray -> Decoded"
    PRINT "-------------------------"

    i = 0
    WHILE i < 16
        bin_val = i
        gray_val = bin_val XOR (bin_val / 2)
        decoded_val = gray_val
        temp_val = gray_val / 2
        WHILE temp_val <> 0
            decoded_val = decoded_val XOR temp_val
            temp_val = temp_val / 2
        WEND

        temp_str = STR$(bin_val)
        PRINT "  " + temp_str + " -> " + STR$(gray_val) + " -> " + STR$(decoded_val)

        i = i + 1
    WEND

    PRINT ""
    PRINT "XOR bit operations:"
    temp_str = STR$(5 XOR 3)
    PRINT "  5 XOR 3 = " + temp_str
    temp_str = STR$(12 XOR 7)
    PRINT "  12 XOR 7 = " + temp_str
    temp_str = STR$(255 XOR 128)
    PRINT "  255 XOR 128 = " + temp_str

    PRINT ""
    PRINT "Gray code sequence (0-15):"
    PRINT "  "
    i = 0
    WHILE i < 16
        gray_val = i XOR (i / 2)
        PRINT STR$(gray_val) + " "
        i = i + 1
    WEND

    PRINT ""
    PRINT ""
    PRINT "Binary reflected Gray code properties:"
    PRINT "  Consecutive values differ by 1 bit"
    PRINT "  Cyclic: first and last also differ by 1 bit"

    bin_val = 7
    gray_val = bin_val XOR (bin_val / 2)
    PRINT "  Binary " + STR$(bin_val) + " -> Gray " + STR$(gray_val)

    bin_val = 8
    gray_val = bin_val XOR (bin_val / 2)
    PRINT "  Binary " + STR$(bin_val) + " -> Gray " + STR$(gray_val)

    PRINT ""
    PRINT "Hamming distance (Gray neighbors):"
    i = 0
    WHILE i < 15
        gray_val = i XOR (i / 2)
        temp_val = (i + 1) XOR ((i + 1) / 2)
        temp_str = STR$(gray_val XOR temp_val)
        IF i < 10 THEN
            PRINT "  " + STR$(i) + "-" + STR$(i + 1) + ": diff = " + temp_str
        END IF
        i = i + 1
    WEND

    PRINT ""
    PRINT "Gray code demo complete."

    FUNCTION = 0
END FUNCTION
