10 REM BRAINFK INTERPRETER FOR GW-BASIC 20 INPUT "File to open? ",INFILE$ 30 DIM TAPE(10000): REM memory is 10000 long 40 DIM PRG$(5000): REM programs can be 5000 symbols long 50 PRG$ = "" 60 OPEN(INFILE$) FOR INPUT AS #1 70 S = 0 : REM instruction pointer 80 WHILE NOT EOF(1) 90 LINE INPUT #1, LIN$ 100 FOR P = 1 TO LEN(LIN$) 110 C$=MID$(LIN$,P,1) 120 IF C$="+" OR C$="-" OR C$="." OR C$="," OR C$ = "<" OR C$=">" OR C$="[" OR C$="]" THEN S=S+1:PRG$(S)=C$ 130 NEXT P 140 WEND 150 PRLEN = S 160 REM ok, the program has been read in. now set up the variables 170 P = 0 : REM tape pointer 180 S = 1 : REM instruction pointer 190 K = 0 : REM bracket counter 200 WHILE S<=PRLEN: REM as long as there are still instructions to come 210 IF INKEY$="Q" THEN END 220 IF PRG$(S) = "+" THEN GOSUB 320 230 IF PRG$(S) = "-" THEN GOSUB 350 240 IF PRG$(S) = ">" THEN GOSUB 380 250 IF PRG$(S) = "<" THEN GOSUB 420 260 IF PRG$(S) = "." THEN GOSUB 460 270 IF PRG$(S) = "," THEN GOSUB 490 280 IF PRG$(S) = "[" THEN GOSUB 650 ELSE IF PRG$(S) = "]" THEN GOSUB 550 290 S = S + 1 300 WEND 310 END 320 REM the + instruction 330 TAPE(P) = TAPE(P) + 1 340 RETURN 350 REM the - instruction 360 TAPE(P) = TAPE(P)-1 370 RETURN 380 REM the > instruction 390 P = P + 1 400 IF P > 10000 THEN P = P - 10000 : REM circular tape, because why not? 410 RETURN 420 REM the < instruction 430 P = P - 1 440 IF P < 0 THEN P = P + 10000 450 RETURN 460 REM the . instruction 470 PRINT CHR$(TAPE(P)); 480 RETURN 490 REM the , instruction 500 BEEP : REM use the beep as a signal that input is expected 510 G$ = INKEY$ 520 IF G$ = "" THEN GOTO 510 530 TAPE(P) = ASC(G$) 540 RETURN 550 REM the ] instruction 560 IF TAPE(P)=0 THEN RETURN : REM do nothing 570 K = 1 : REM otherwise it's some bracket counting 580 WHILE K > 0 590 S = S - 1 600 IF S = 0 THEN PRINT "Backtrack beyond start of program!" : END 610 IF PRG$(S) = "]" THEN K = K + 1 620 IF PRG$(S) = "[" THEN K = K - 1 630 WEND 640 RETURN 650 REM the [ instruction 660 IF TAPE(P)<> 0 THEN RETURN 670 K = 1 680 WHILE K>0 690 S = S + 1 700 IF S>PRLEN THEN PRINT "Advance beyond end of program!" : END 710 IF PRG$(S) = "]" THEN K = K - 1 720 IF PRG$(S) = "[" THEN K = K + 1 730 WEND 740 RETURN