REM
REM Brainfuck interpreter - http://en.wikipedia.org/wiki/Brainfuck
REM
REM Created on 17/4/2009 - PvE
REM Revised November 2009.
REM Revised December 2009.
REM Revised May 2010.
REM Revised October 2012 - PvE.

REM Get the separate arguments
SPLIT ARGUMENT$ BY " " TO arg$ SIZE dim

IF dim < 2 THEN
    PRINT "Usage: bf <file>"
    END
ENDIF

REM Determine size
filesize = FILELEN(arg$[1])

REM Get the contents
OPEN arg$[1] FOR READING AS bf

REM claim memory
txt = MEMORY(filesize)

REM Read file into memory
GETBYTE txt FROM bf SIZE filesize

CLOSE FILE bf

REM Initialize work memory
mem = MEMORY(30000)

REM This is The Pointer pointing to memory
thepointer = 0

REM This is the cursor pointing in the current program
cursor = 0

REM Start interpreting program
WHILE cursor < filesize DO

    command = PEEK(txt + cursor)

    SELECT command
        CASE 62
            INCR thepointer

        CASE 60
            DECR thepointer

        CASE 43
            POKE mem + thepointer, PEEK(mem + thepointer) + 1

        CASE 45
            POKE mem + thepointer, PEEK(mem + thepointer) - 1

        CASE 46
            PRINT CHR$(PEEK(mem + thepointer));

        CASE 44
            key = GETKEY
            POKE mem + thepointer, key

        CASE 91
            jmp = 1
            IF ISFALSE(PEEK(mem + thepointer)) THEN
                REPEAT
                    INCR cursor
                    IF PEEK(txt + cursor) = 91 THEN
                        INCR jmp
                    ELIF PEEK(txt + cursor) = 93 THEN
                        DECR jmp
                    END IF
                UNTIL PEEK(txt + cursor) = 93 AND NOT(jmp)
            END IF

        CASE 93
            jmp = 1
            IF ISTRUE(PEEK(mem + thepointer)) THEN
                REPEAT
                    DECR cursor
                    IF PEEK(txt + cursor) = 93 THEN
                        INCR jmp
                    ELIF PEEK(txt + cursor) = 91 THEN
                        DECR jmp
                    END IF
                UNTIL PEEK(txt + cursor) = 91 AND NOT(jmp)
            END IF
    END SELECT

    INCR cursor
WEND