' Ring buffer (circular buffer): write, read, peek, overflow detection
#COMPILE EXE
#DIM ALL

FUNCTION PBMAIN() AS LONG
    DIM buf(1 TO 16) AS BYTE
    LOCAL head AS LONG
    LOCAL tail AS LONG
    LOCAL size AS LONG
    LOCAL i AS LONG
    LOCAL b AS LONG
    LOCAL readBack AS STRING
    LOCAL pos AS LONG
    LOCAL idx AS LONG

    PRINT "=== Ring Buffer ==="
    PRINT

    head = 1
    tail = 1
    size = 0
    PRINT "Write 'Hello Ring':"
    FOR i = 1 TO LEN("Hello Ring")
        buf(tail) = ASC(MID$("Hello Ring", i, 1))
        tail = (tail MOD 16) + 1
        size = size + 1
    NEXT i
    PRINT "  Buffer size: " & FORMAT$(size) & "/16"
    PRINT

    readBack = ""
    FOR i = 1 TO size
        b = buf(head)
        readBack = readBack & CHR$(b)
        head = (head MOD 16) + 1
    NEXT i
    size = 0
    PRINT "Read back: " & readBack
    PRINT

    head = 1
    tail = 1
    size = 0
    FOR i = 1 TO 16
        buf(tail) = 65 + (i MOD 26)
        tail = (tail MOD 16) + 1
        size = size + 1
    NEXT i
    PRINT "Fill buffer (16 bytes): size=" & FORMAT$(size)
    IF size = 16 THEN PRINT " full=Yes" ELSE PRINT " full=No"
    PRINT

    buf(tail) = ASC("X")
    tail = (tail MOD 16) + 1
    head = (head MOD 16) + 1
    size = 16
    PRINT "Overwrite (add 'X'): head=" & FORMAT$(head) & " tail=" & FORMAT$(tail)
    readBack = ""
    FOR i = 1 TO size
        b = buf(head)
        readBack = readBack & CHR$(b)
        head = (head MOD 16) + 1
    NEXT i
    size = 0
    PRINT "Read back: " & readBack
    PRINT

    b = buf(head)
    PRINT "Peek at pos 0: " & CHR$(b)
    pos = head
    pos = pos - 1
    IF pos < 1 THEN pos = 16
    b = buf((head MOD 16) + 1)
    PRINT "Peek at pos 1: " & CHR$(b)
    PRINT

    PRINT "Ring buffer tests complete."
    FUNCTION = 0
END FUNCTION
