Chipmunk Basic Readme & Quick Reference


** ** Chipmunk Basic README ** **   (version 3.6.6b0, 2012-Apr) 

Chipmunk Basic is a old-fashioned interpreter for the BASIC
programming language.  This is a beta release of a terminal
command-line utility plus a text window application for Mac
OS X.  Note that  Chipmunk Basic 3.6.7 for macOS/OSX 10.9.x
and later has been rewritten for Cocoa, and thus is missing
many of the features and special macfunctions in the old
Carbon port.

Features of the Mac OS X Carbon window port include support for
simple graphics with a sprite graphics engine, sound, MacinTalk
speech.  It's also AppleScriptable.  A te2cbas AppleScript
is included to run programs from the TextEdit application.
A tw2cbas AppleScript is included to run programs from the
TextWrangler application.

Please see basic.man.txt for documentation of the Basic language.
Please see the quick-ref for Mac specific features.

Use the Terminal utility to run the command-line version (The
Terminal utility is in the Mac OS X Applications / Utilities
folder.)  The command-line executable named "basic" can go into your
/usr/bin directory ( use: sudo mv -i basic /usr/bin/basic ), or any
other directory in your execution $path.  The basic.1 man file goes
into your /usr/share/man/man1/ directory.  Then type "man basic"
to see the man file in readable form.  Note that from the Terminal
or any unix shell, you can use the command "basic filename.bas"
to run a Basic program, and that externally edited Basic program
do not need to have or use line numbers.

Every personal computer should come with a simple, easy to learn,
programming language.  Chipmunk Basic was my contribution for the
very first PowerMacs.  Chipmunk Basic only comes with a man page and
a quick reference to the Mac specific functions.  The language is
mostly compatible with books on programming in BASIC that were
written between around 1978 and 1990. This version is a both bug
fix and new feature release.  It is still free for educational and
non-commercial distribution and use (but only for those who don't
believe that using the BASIC language causes brain damage. :-)

Please send bug reports to 
More documentation and possible updates can be found on the
Chipmunk Basic Home Page:     

Shortened version history:

Version 1.367.26xx: 	(2016)
        fixes for serial IO, fn midi and utf8 print
	added beta support for BLE/Bluetooth LE

Version 3.6.7(b2): 
        fixes for Intel 64-bit port
Version 3.6.7(b0): 
        beta port for Cocoa (OS X 10.7 and later) with threading
	removed PPC support
Version 3.6.6(b0):  	(2012)
 	fixed a gosub error message
        fixed some graphics commands under OS X 10.7
	added mat read, fixed mat assign bug
Version 3.6.5(b3):  	(2011)
        fixed mat multiply
        fixed bug in format$() with leading zeros
        fixed bug in exit while statement
        fixed bugs in empty for and empty edit statements
        fixed object string bug
Version 3.6.4(b8): 
        fixed problems with fn plot1, format$, string objects
	added command: graphics arc x,y,r,a1,a2
Version 3.6.4(b7): 
        fixed some mat command syntax omissions
        fixed a function subroutine return bug
        allow subroutines to return 1d and 2d mat arrays
        added beta test object arrays
Version 3.6.4(b6): 
	added def local
Version 3.6.4(b5): 
        added a TextWrangler AppleScript utility
        allow restore command to use a labeled line
        added fn playsound() to play sound files
        fixed sound command for some multivoiced tones
        fixed graphics pict to work with more image files
        added fn eval()
        added #ifndef _chipmunkbasic_ to ignore code
        fixed documentation on 2 parameter atan()
Version 3.6.4(b1): allow larger bload/bsave file sizes
        added det() function to calculate 2d matrix determinants
        added fn dot(a,b) to calculate 1d vector dot product
        allow mat inv of larger matrices
        allow larger bload/bsave file sizes
        allow if-then else syntax without a colon :
        allow comments at beginning of if-endif statement blocks
        improved fn sleep() timing
        fixed some bugs in format$() and print using
        fixed default save button highlight in Mac Intel build
Version 3.6.3(b1): added fn fft1(), fixed get & randomize/rnd bug
Version 3.6.3(b0): added dbm database command, fixed fn math$() bug,
        fixed macfunction "putstr2clip"
Version 3.6.2(b9): fixed del bug, graphics window bug, format$(),
        MacOS X Intel port + random file byte order fix, fn version$()
Version 3.6.2(b5): added system$(), fn version$, open pipe for output,
        fixed atn() bug, fixed Mac bundle name & icon, savepicture
Version 3.6.1(b3): fixed integer LET command bug
        added morse, say, sound & com1: support to command-line basic
        documented fseek command
Version 3.6.1: changed exponentiation precedence, default mat origin
        added mat print command
Version 3.6.0: added exit status, fn kill(), fn bigendian(),
        added Carbon graphics scrn() function.
        Included an AppleScript for use with TextEdit
Other additions:
    unix socket() and pipe i/o functions
    Carbon window: serial port i/o, sound recording,
        saved preferences for font, changed path used for "Save As"
Version 3.5.9b4: added two parameter atn()
Version 3.5.9b2: fixed "Save As", intl. string compares
Version 3.5.8b4: fixed inkey$. changed int() to round to -infinity.

 * Chipmunk Basic is Copyright 1994-2016 by Ronald H. Nicholson, Jr.
 * ALL RIGHTS RESERVED
 *
 * Permission to use, copy and distribute this software without fee
 * for non-commercial or educational purposes is hereby granted,
 * provided that the above copyright notice appear in all copies,
 * and that both the copyright notice and this permission notice with
 * the following disclaimer appear in the supporting documentation.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY OF ANY KIND; not even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR ANY PARTICULAR PURPOSE.
 
 * Portions of this version of Chipmunk Basic might be
 *   Copyright (c) 1983 Regents of the University of California.
 * Portions of Chipmunk Basic might be Copyright (C) 1989 Dave Gillespie.

-- cut here --
/*
 * Quick Reference and FAQ for Chipmunk Basic  
 *   version 3.6.6 for MacOS X 
 *
 * Chipmunk Basic is (c) Copyright 1994-2016 Ronald H. Nicholson, Jr.
 * ALL RIGHTS RESERVED
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY OF ANY KIND; not even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 */

Updates to this document may be found on the web at:
  http://www.nicholson.com/rhn/basic

---
Quick Reference for Chipmunk Basic
ported to the MacOS by Ronald H. Nicholson, Jr.	  rhn AT nicholson.com 

Chipmunk Basic is a freeware old-fashioned Basic Interpreter, accelerated
for the PowerMac, yet still compatible with older 68k Macs running OS 9.
Features include support for a simple sprite graphics engine, sound,
MacinTalk speech, MacTCP, AppleScript, Drag&Drop and OOP programming.

Supported operators, functions and statements (reserved words):

        + - * / ^ mod  and or xor not  > < >= <= <> =
        sqr() log() exp() sin() cos() tan() atn()  pi
        abs() sgn() int() rnd() peek() val() asc() len()
        mid$() right$() left$() str$() chr$()  lcase$() ucase$()
        goto  if then else endif  gosub return
        for to step next  while wend  select case
        rem  let  dim erase  data read restore   field$()
        input print open for output append as close# load save
        random lof loc get put   
        inkey$  input$ eof()  files  fgetbyte# fseek# fputbyte
        run stop end exit quit cont  renum  new clear
        date$ time$ timer  sound morse say  doevents inputbox
        home cls gotoxy htab vtab pos()  menu
        graphics sprite pset moveto lineto window scrn mouse()
        varptr peek() poke fre push() pop  isarray  mat
        sub call usr  bload bsave  def fn  local  exec
        type class extends  string integer single double longint
        asin acos sinh cosh tanh log10 floor true false ubound


- The "basic.man" file is included with the distribution.  It
  describes the above functions and statements in more detail.
  
- Line numbers are required for console input.
- Line numbers are NOT required when using BBEdit with BBEdit Extensions
  or other external editor (TextEdit, vi).  An applescript named "te2cbas"
  is included which will run a Basic program contained in the topmost
  Mac OS X TextEdit text editor window.

- The interpreter includes an dumb old fashioned line number based
  editor.  (Enter a line; delete a line; edit one line at a time).
- The variable types are float doubles and strings with a maximum
  length of 254 characters.  Variable names can be up to 31 characters
  in length and are case insensitive.
- Math is done using the built-in double precision IEEE math.
  All trigonometric functions express angles in radians.

---
Some Simple Examples:

  for i=1 to 10 : print i : next i

  c$ = a$ + b$              : rem string concatenation
  a$ = inkey$               : rem inkey$ is non-blocking 
  
  load "sieve.bas"          : rem load TEXT file as a Basic program
                            : rem file names should have .bas extension
  
  open "filename" for output as #1 : print #1, "hello world" : close #1 
  
  graphics 0  : moveto 10,10 : lineto 110,80	: rem draw a line
  
---
Frequently Asked Questions:

Q: Where is there more documentation on learning how to program in the
   BASIC language?
A: The language is mostly compatible with books on programming in the
   BASIC language that were published between 1978 and 1988.  Since these
   are mostly out of print, your best bet is to try your local public
   library.
   
   Also, there is a short tutorial on the Chipmunk Basic web page:
        http://www.nicholson.com/rhn/basic/

Q: Why won't this Mumblesoft QuickBasic program run? ...
A: Chipmunk Basic was never intended to be exactly compatible with any
   other commercial BASIC language product.  It does include most of the
   features of ANSI minimal BASIC language definition.  Many BASIC
   programs that are saved as ASCII text files, and that don't use any
   special features of a particular computer OS, can be easily ported
   to Chipmunk Basic.
   
Q: Is there any way to redirect print statements to a line printer?
A: No, there is no way to make this work with current MacOS printer
   drivers. I recommend printing to a file, and then using SimpleText
   to print the file.

Q: Why can't I load a text file using the "Open" menu?
A: Chipmunk Basic requires that Basic program file names end with a
   ".bas" suffix.
   
Q: How do I use BBEdit (so that I don't need to use line-numbers).
A:  Install BBedit Lite (or BBEdit) on your system with Chipmunk Basic.
    A folder named "BBEdit Lite Support" should appear with BBEdit.
    Copy the bbxt named "bb2cbas" from the "bbedit2cbas.hqx" archive
    into the "BBEdit Extensions" folder.  Start BBEdit; and enter a
    program using BBEdit; then use the "Run Chipmunk Basic" item in
    the BBEdit Tools menu to send your program text to the Chipmunk
    Basic interpreter.  BBEdit Lite is available on Info-Mac and many
    other software archives and at the Bare Bones Software(tm) web
    site: 

Q: How do I use sprites?
A: Sprite are little icons that can be moved around in the graphics
   window.  You can use up to 63 sprites, numbered from 1 to 63  Sprites
   will appear in front of any graphics or picts in the graphics window.
   The sprites are in layers; sprite 1 will pass in front of sprite 2
   when they overlap, etc. 
   
   You specify what you want a particular sprite to look like by using
   a resource ID.  For instance a sprite with a resource id of 28 looks
   like the Chipmunk icon, with a resource id of 130 looks like a ball.
   A sprite with with a rsrc id of 0 is invisible.
   
   You can also specify the filename of a .jpg or .gif file to use
   for the sprite image.
   
   You may place sprites at an x,y coordinate.  Or you may move them
   around and leave a trail behind them to draw things.  Sprite movement
   commands include { up, down, left, right, forward, turn, turnleft,
   turnright, turnto, penup and pendown }.  To get rid of a sprite,
   simply move them offscreen (e.g. { x,y } = { -1,-1} ).

Q: How do I make my own sprites?
A:  You can now use gif and jpeg image files as sprites.

Q: Why can't I read the character chr$(13) from a file?
A: The Mac standard c library translates CR characters (0x0D) into LF
   characters (0x0A) when reading or writing text files.  Open a binary
   file for "data input" or "data output" to turn off this translation.

Q: Can you send me a list of different peeks and pokes?
A: Peeks and pokes don't have much use on current Mac Systems.  If you
   want to live dangerously, you might want to get a copy of SysEqu.h or
   LoMem.h from an old C or 68K assembly language programming package;
   but don't expect anything you do to be compatible with the latest
   MacOS System software.

Q: Is there a compiler for Chipmunk Basic?
A: No, however there are several commercial Basic compilers on the market
   (Staz FutureBasic, True Basic, VIP Basic, Oracle Power Objects ...)
   and rumors of major new support for the BASIC language on the Mac
   coming next year (1997 maybe ?,  Kenobi ??, Denali ??? ... ).
   
Q: Why isn't this cool command that I found documented.
A: Any undocumented command is fair game to change in the next version.
   Use at your own risk: Hey, even some of the documented commands change!

Q: (not really a question) The documentation s*cks...  uh, stinks.
A: I'm crazy enough to have found that tinkering with and enhancing
   Chipmunk Basic has been enjoyable use of some spare time.  If you
   are enlightened enough to enjoy writing quality documentation, please
   feel free to contribute your efforts.

Q: What is the history of Chipmunk Basic?
A: In March 1990, p2c, a pascal to c translator, was posted to the usenet
   newsgroup "comp.source.misc" by David Gillespie.  One of the test
   input files was "basic.p".  I used the output c file to learn about
   language interpreters; and then ported the resulting Basic interpreter
   to a Mac 512KE and then to a PowerMac 7100.  Chipmunk Basic for
   the PowerMac was posted to Info-Mac on March 15th, 1994, the day
   after the first PowerMacintosh was available for sale to the public.

---
Additional Chipmunk Basic Macintosh specific commands and functions:

Note that Chipmunk Basic 3.6.7 for macOS/OSX 10.9.x and later
has been rewritten for Cocoa, and thus is missing many of the
features, and all of the special macfunctions for the old
Carbon window port of Chipmunk Basic 3.6.6 mentioned below.

- Mac Graphics

        GRAPHICS 0                          	:' show graphics window
        graphics -1                        	:' hide graphics window
        graphics WINDOW x, y, width, height	:' graphics window setup
                                :' (x,y) location, width and height
        graphics WINDOW width, height	        :' adjust the size

        graphics MOVETO  x,y	        :' Move pen To x,y
        graphics LINETO  x,y	        :' draw Line To x,y
        
        graphics moveto 10,20 : graphics lineto 30,50	:' example
                        :' that draws a line from (10,20) to (30,50)

        graphics CIRCLE  x	        :' circle of diameter x
                        :' previous MOVETO x,y s ets center location
        graphics OVAL    x,y        	:' oval  x wide by y high

        graphics RECT  x1,y1, x2,y2        	:' FrameRect
        graphics FILLRECT  x1,y1, x2,y2,pat#	:' PaintRect
        graphics FILLRECT  x1,y1, x2,y2,-1	:' EraseRect
        graphics OVAL  x1,y1, x2,y2	        :' FrameOval
        graphics FILLOVAL  x1,y1, x2,y2,pat#	:' PaintOval
        graphics PENSETUP  xsize, ysize [, mode, pat# ] :' modes 8-15
                :' modes - 8 patCopy, 9 patOr, 10 patXor, 11 patBic
                :' pat# - 1 is black, 4 is 50% dots, 12 is bricks, etc.

        graphics COLOR  r,g,b	        :' red green blue 0-100%
        graphics COLOR 100,0,0	        :' changes new color to red
        graphics COLOR  0,0,0	        :' use default black

        graphics pset x,y	                :' plot 1 point at x,y
        graphics TRIANGLE x1,y1,x2,y2,x3,y3 {,r,g,b}  :' draw triangle
        graphics PICT   x,y, n	        :' draw 'pict' resource# n
        graphics PICT   x,y, pictfilename$	:' draw .pict file

        graphics DRAWTEXT  a$	        :' DrawText
                :' use MOVETO x,y  to position text lower left corner
        graphics TEXTSETUP f, s, m	:' set up text font, size, mode
        graphics TEXTSETUP -1,-1	:' set up bold font
        graphics TEXTSETUP -1,-2	:' set up italic font
        graphics TEXTSETUP -1,0		:' restore normal font

        graphics (-38)	            :' return graphics window max width
        graphics (-39)	            :' return graphics window max height
        graphics (-34)	            :' return graphics window pixel depth
        
        fn scrn(x, y, 0)	    :' return graphics pixel value at x,y
        fn scrn(x, y, 1)	    :' return red component
        fn scrn(x, y, 2)	    :' return green component
        fn scrn(x, y, 3)	    :' return blue component
        	:' may need to wait at least 1/4th of a second
        	:'  for the scrn function to return any recently drawn pixels
        	:' the graphics 0 command may hasten the display update

        SPRITE	n  x, y, id	    :' sprite n @ x,y using ICN# id
                                    :' n from 1 to 63, 1 frontmost
                                    :' ICN# 128 - 141 included with app
                                    :' cicn requires ICN# with same id.
        sprite	n  UP    x	    :' sprite #n move up x pixels
        sprite  n  DOWN  x	    :'   also returns new sprite y coord
        sprite  n  LEFT  x	    :' move LEFT (not turn as in Logo!)
        sprite  n  RIGHT   x
        sprite	n  TURN    d	    :' turn counter-clockwise d degrees
        sprite	n  TURNRIGHT d	    :' turn clockwise d degrees
        sprite	n  TURNLEFT  d
        sprite	n  TURNTO    d	    :' turn to d degrees from x axis
        sprite	n  FORWARD x	    :' move forward x pixels
        sprite	n  PENUP
        sprite	n  PENDOWN
        sprite	n  COLLISION	    :' returns 1st sprite# in contact
        sprite  id  on  x,y	    :' paste a fixed sprite image @(x,y)

        graphics WINDOW -1,-1, x,y, 2	:' scroll graphics background

        ' Too small a "Preferred Size" (as set from Finder Get Info window)
        ' may limit the maximum graphics window size.
        ' Under Mac OS X, execute these commands, then exit and restart to
        ' try and increase maximum graphics window size.
        
      	macfunction("putPref","gwindow.w.max","2048") : rem width
      	macfunction("putPref","gwindow.h.max","2048") : rem height
      	
        macfunction ( "savepicture", fname$ )
                        :' saves graphics window to a PICT file
                        :' use graphics window command to set size
	fn saveaspng(fname$, x,y, w,h)
                        :' saves pixels to a PNG file
			:' preceed with graphics 0 + wait 1 second 
			:' with white as transparancy
	fn saveaspng(fname$, x,y, w,h, 32896)
			:' with 50% grey as transparancy

        graphics PICT x,y, filename$
                        :' draws graphics from image file at (x,y)
                        
        graphics 0	:' refresh graphics window now
        		:' for control of graphics animation update rate
        
- Mac Sound commands

        morse "CQ DE N6YWU",16,40,13,700        :' play morse code
                :' MORSE string, dot_wpm, volume, letter_wpm, freq
  
        say "hello world"            :'  *requires* the Speech Manager
        say "faster", 196, 44, 1    :'  string, rate, pitch, voice#
        say        	:' reads the last 12 lines of the console window
        x  = macfunction("numSpeakers")	:' the number of voices
        v$ = macfunction("getSpeaker")	:' get the voices name

        sound 440, 0.5, 30	:' freq, secs_duration, vol(0-100)
        
        sound 0, 8192	        :' play snd resource #8192
        sound n,freq(0),dur,vol(0) :' play n tones from arrays freq & vol
                :' 1 < n < 9 => up to 8 multivoice tones (chords)
                
        ' Quicktime MIDI sound
        
        sound -2, midi_voice, midi_key, velocity, secs_dur [,channel]
                :' play note using Quicktime MIDI synthesizer
                :' midi_voice = 1 -> piano
                :' midi_key = 60 -> middle C
                :' midi_velocity = 100 -> loud
                :' simultaneous channels 1 to 4 supported
		:' default channel is 1
        sound -3, midi_voice, midi_key, velocity, secs_dur [,channel]
                :' wait for previous note to finish then play
        sound -4, midi_voice, midi_key, velocity, secs_dur
                :' play on any free channel without waiting

        fn playsound( fname$, n )
                :' play up to n seconds from sound file fname$
                
        ' sampled sound support
        
        sound -1, a(0), n   :' play n samples from array a()
                            :' at sample rate 11025
        sound -1, a%(0), n, 44100, 16	:' play sampled sound
                            :' 16 bit quality at 44100 sample rate
        
        fn record(a(0),n)
        fn record(a%(0),n)
        	:' records n samples of sound into a() or a%()
        	:' 	16-bit quality at a sample rate of 11025
        fn record(a%(0),n, 44100)
        	:' 	record 16-bit mono at a sample rate of 44100
	
- Mac User interface functions and commands
        
        cls	                : rem clears console & graphics windows
        gotoxy 5,10 : print "here" : rem move text cursor (0,0 origin)
        x = pos(0)	        : rem text cursor horizontal location
        y = pos(-1)	        : rem vertical text cursor location

        a$ = inputbox("prompt", "title", "default", 0)
                :' gets string input using default dialog
        a$ = inputbox("prompt", "title", "default", id)
                :' if id > 1024 this will use a custom DLOG #id
                :'    with item 1 = OK, item 2 = cancel
                :'    prompt replaces 1st static text item
                :'    default replaces 1st edit text item
                
        macfunction("wintitle", t$)	:' sets the graphics window title
        macfunction("bigfont")	:' toggles BIGFONT console output status
        macfunction("hideMenuBar")
        		:' hides menubar. graphics -1 to restore.
        
        mouse(0)        ' returns 1 if the mouse button is down
        mouse(1)        ' x coordinate in current window
        mouse(2)        ' y coordinate in current window
        mouse(3)        ' last x click location (set to -1 after read)
        mouse(4)        ' last y click location (set to -1 after read)
                :' mouse() must follow a graphics command
                :'   to get a location in the graphics window.

        graphics BUTTON title$, x,y, w,h, key_code
                        :' draw a standard button at (x,y) size (w,h)
                        :' will input chr$(key_code) when pressed
        graphics BUTTON title$, x,y, w,h, e$
                        :' button will exec(e$) when pressed
        graphics BUTTON "",-1	        :' remove all buttons & sliders

        menu 4, title$, itemlist$, eventlist$	         :' setup menu
        menu 4, "myMenu", "item1;item2", "foo1();foo2()" :' example
                :' sets up the 4th menu (only 4th menu is implemented.)
                :' calls your subroutines foo1() & foo2() on menu select.
                :' subroutines must be previously defined.
                :' see Apple documentation for menu options
        menu 4, ""        :' removes your menu
        fn doevents()     :' poll for button and menu events

- Additional Mac specific functions and commands:

        open "SFGetFile" for input as #2    :' dialog prompt for filename
        open "SFPutFile" for output as #5   :' uses dialog box for name
        open f$ for data input as #4	:' data file, no CR-LF translation
        open f$ for data input  :' use file for snd & pict, etc. resources
        a$ = field$("aa bb cc", 2, " ")	:' returns "bb", (awk fields)
        a$ = field$(a$, n, chr$(9))     :' return nth item in TSV line a$

        s$ = macfunction("getclipstr")	        :' get clipboard text
        s$ = macfunction("putstr2clip")	        :' put text into clipboard

        x = macfunction("NoLineNums",1)
        			:' turns off line numbers in list & save

        fn sleep(t)				:' sleep for n seconds
 
        reply$ = macfunction("Gestalt","cput")  :' system gestalt info
        x = macfunction("keydown", 0x3a)        :' test option key

        x = macfunction("launch", appname$)     :' launch an app in local dir
        
        macfunction("rsrcload",fname$, rtype$, id, i%(0), sizelim, 2)
        	:' loads rsrc data into an integer array & returns size
        macfunction("rsrcsave",filename$, restype$, res_id, i%(0), size)
        	:' saves the contents of an integer array as a resource

	graphics window 200,200,32,32 : ... : macfunction("copyPict") :
	macfunction("rsrcsave", filename$, "PICT", rsrc_num)
		:' saves contents of a small window as a PICT resource

        fre	:' returns available heap memory.
                :' If this gets much below 32K, one should increase the
                :'   Preferred size using Finder Get Info & restart Basic.

- AppleScript scripting.  Try this script from a script editor:

        tell application "chipmunk-basic" to DoScript "eval ( 5 * 7 )"
        tell application "chipmunk-basic" to DoScript "eval date$"
            :' eval will return a string result to the script editor.
        tell application "chipmunk-basic" to DoScript "print 22 * 7"
        tell application "chipmunk-basic" to DoScript "say 'hello'"
            :' Tells Chipmunk Basic to executes a statement.
        tell application "chipmunk-basic" to DoScript ("runStatus")
	    :' returns whether a Basic program is running
	    
- ICN#, cicn, PICT & BCMD resources may be stored the resource fork of
        any file, not just the "mumble.bas" program file.  Use:
        open "foo.rsrc" for data input : rem with no "as" token,
           :' this makes the file "foo.rsrc" the current resource file

- A few experimental commands which may only work in OS X 10.2 or above :

        macfunction ( "DrawFromFile", fname$, x, y )
                        :' draws graphics from JPG or GIF file at (x,y)

        open "COM1:/dev/cu.modem:1200,N,8,1" for output as #1
        open "COM1:/dev/cu.modem:1200,N,8,1" for input as #2
        	:' opens serial port with given unix path and baud rate
 	
        fn serialpath(n)
        	:' returns the path string for the n-th serial port
        	:'  starting with 1 (usually the internal modem)
        	:'  example:
        	100 rem serial i/o example
        	120 sp1$ = fn serialpath(1) : print sp1$
        	130 if sp1$ = "" then stop
        	140 sp2$ = fn serialpath(2) : print sp2$
        	160 config$ = "COM1:" + sp1$ + ":9600,N,8,1"
        	180 print config$ : print
        	200 open config$ for input as #2
        	220 open config$ for output as #1
        	240 k = 0
        	260 while k <> 3 : rem control-C to exit
        	280   a$ = input$(1,2)
        	320   print a$;
        	340   k$ = inkey$ : k = asc(k$)
        	360   if (k > 3) then fputbyte k,#1
        	380 wend
        	420 close #2 : close #1
        	440 print : print "done"
        	460 end
	
        :' Note that Chipmunk Basic unix pipes and sockets also work
        :' under OS X .  See the man page for details.
        
        open "socket:www.yahoo.com",80 for input as #1
        open "socket:www.yahoo.com",80 for output as #2
        		:' open tcp/ip socket to a web server
		
        sys(command$)	:' execute unix terminal command
        		:'   no stdout/output provisioned

        system$(command$)	:' execute unix terminal command
        			:' returns 1st line of standard output

        dir	
        	:' displays files in current working directory

- A few experimental Database commands (beta test) :
 
        dim mydb$ as dbm$(myfname$)
            :' creates an sdbm hash database named by myfname$
            :' using string variable name mydb$ to access
        mydb$(key$) = val	:' stores key,value pair in db
        close mydb$		:' to close database

- A few other experimental commands & functions (beta test) :

        fn version$()	:' returns version & graphics capability
        		
        ' To change the command console window's location & size, try:

      	macfunction("putPref","cwindow.x","100") : rem x location
      	macfunction("putPref","cwindow.y","200") : rem y location
      	macfunction("putPref","cwindow.w","800") : rem width in pixels
      	macfunction("putPref","cwindow.h","500") : rem height in pixels

        graphics edit a$, x,y, w,h, id
        	:' creates edit text field in the graphics window
        	:' location x,y  size w,h
        	:' id must be in the range of 1 thru 4
        	:' a$ must be a string variable
        	
        graphics edit a$, 0,0, 0,0, id
        	:' returns content of field #id into a$
        
        macfunction("getpixels", a%(0), x,y, w,h)
        	:' read raw graphics pixels into array a%()
        	:'   screen location x,y  rectangle size w,h
        	:'   each pixel uses 2 16-bit array words
              
        macfunction("putpixels", a%(0), x,y, w,h)
        	:' draw raw pixels from array a%() to x,y
        	:'   each pixel uses 2 16-bit array words
        macfunction("putpixels", a%(0), x,y, w,h, z)
        	:'   draw fatbits using zoom factor z
              
        macfunction( "drawutf16str", t%(0), len, x, y )
        	:'   draw UTF character string from integer array

        fn midiinput(n)		:' was macfunction( "midiInput", n )
        	:' n = 0 for time (returns 0 if no new note available)
        	:' n = 2 for channel of last note
        	:' n = 3 for note    of last note
        	:' n = 4 for velocity  of last note

        fn midi(2) 	:' init a midi data output channel
        fn midi(3, note, velocity) 	
		:' send midi noteon/off
		:' set velocity to 0 for noteoff

        fn fft1( 1, x(0), y(0), n )
        	:' fft arrays x,y (real & imaginary vectors, length n)
        	:' n must be a power of 2, array sizes must be >= n
        fn fft1(-1, x(0), y(0), n )
        	:' inverse fft
        	
        macfunction("fft2", real(0),imag(0), n)
        	:' fft of complex data
        	:' n must be a power of 2, array sizes must be >= n
        	:' other commands: "ifft2" for inverse fft
        
        macfunction("fft_polar", real(0),amp(0),phase(0), n)
        	:' fft of real data, returns amplitude & phase
        
        fn plot1( 0, f$, x$, y$, x0, x1, n)
        	:'   draw autoscaled xy plot
        fn plot1( 0, "sin(x)", "x", "y", 0, 7, 200 )
        	:' plot 200 points from 0 to 7 of sin(x)
        fn plot1( 1, f$, x$, y$, x0, x1, n)
        	:' plot using scaling & grid of previous plot
        fn plot1( 4, f$, a$, r$, a0, a1, n)
        	:' autoscaling polar plot
        fn plot2( 0, n, x(0), y(0) )
        	:' parametric plot of n points from arrays x & y

        x = 0.5
        x2 = fn solve1("2*x=cos(x)", "x")
        	:' attempts to solve for variable "x"
        	:' start by assigning a decent guess to variable
        	:' repeat function call for convergence if necessary
        	:' may work for very "well behaved" functions only!
        		
        fn math$("add$", n$, m$)
        	:' 250 digit precision math on number strings
        	:' commands: "add$" "sub$" "mul$" "div$"
        fn math$("powm", a$, e$, m$)
        	:' commands: "powm" for raise-to-exponent-modulo
        		
        bsave "filename", ptr, len      :' binary memory save
        i = bload("filename", ptr, len) :' binary file load to mem
        	:' use with varptr() to get memory addresses
        		
        fn kill( filename$ )	:' deletes the named file
        	:' returns 0 on success
        		
        sprite 0, id, gif_filename$, x,y, 129
        	:' draw gif/jpeg file as a sprite at (x,y)
        
- A few experimental Core Bluetooth (BLE) functions :
	(beta test, added to versions 3.6.7b6 and later) 

	fn btle.init()
		’ initializes Bluetooth LE/4.0 access
		’ starts a BLE scan
		’ returns 0 if the scan has started
	fn btle.list()
		’ presents a list of discovered BLE peripherals
	fn btle.selected()
		’ returns the UUID string for the selected device
	fn btle.info(n,1)
		’ returns the UUID of the nth listed device
	fn btle.info(n,2)
		’ returns the name of the nth listed device
	fn btle.rssi(n)
		’ returns the RSSI of the nth listed device
	fn btle.connect(1,uuid$)
		’ connects to a BLE device
	fn btle.busy()
		' waiting on a connection, notification or read
	fn btle.connect(1,uuid$,service$,chctrstc$)
		’ connects and requests a notification
	fn btle.request(1,service$,chctrstc$)
		’ read request for a BLE characteristic
	fn btle.response$(1,a%(0))
		’ the read data (if any yet) as a string
		’ set to "" after the first read
	fn btle.responsedata(1,1,a%(0))
		’ the byte count of the read data (if any yet)
		' the bytes are return in integer array
		'   with 2 bytes per array element
		’ set to 0 after the first read
	fn btle.write(1,service$,chctrstc$,data$)
		’ request a write to a BLE characteristic
	fn btle(9)
		’ disconnects from BLE device

    Warning.  Use at your own risk.
    Alpha and experimental commands may go away in future releases.


---
Other notes or Bugs:

- Programs without line numbers can be loaded from a file; however
    sequential line numbers will be added.  The target of a GOTO can
    be a label followed by a colon. e.g.
        foo: print x : x=x-1 : if x>0 then goto foo:
        
- Try the applescript "te2bas" for use with Mac OS X TextEdit.  It
	should run the Basic program in the frontmost TextEdit window.
	
- To save to file without line numbers, try:
	save filename$, "NLN"        : rem - Don't use "goto ".

- Try
		macfunction("putPref","t.bigfont.size","24")
	Then Quit and restart Basic to change the bigfont size.
	
- Try
		macfunction("putPref","gwindow.w.max","2048")
        macfunction("putPref","gwindow.h.max","2048")
	Then Quit and restart Basic to change the max graphics window size.
	
- Other reserved words (don't use these!) :
        msgbox  do loop until break  function
        method private public   dialog memstat()
        draw play   min max  filename$
        each redim resume  static  option degrees radians
        eqv imp key is each set width swap
        
- For the old high precedence NOT operator, enter: #cbas#non_ansi_not
- For the old high precedence unary minus, enter:  #cbas#non_ansi_neg

- All input works like the LINE INPUT statement of other Basic versions.
- Line numbers above 999999999 will not list.
- Transparent buttons do not work.

---
Important Chipmunk Basic Language changes:
  3.6.4:  allow if-then else syntax without a colon :
          allow comments at beginning of if-endif statement blocks
  3.6.1:  lowered unary negation operator precedence to below 
            exponentiation to match ANSI/ISO standard.  (-x^a)
          changed default matrix origin to 1 (used by mat commands).
  3.4.7:  lowered NOT operator precedence to match ANSI standard.
          ON-GOTO no longer checks bounds.
  3.3.7:  type & class vars now require "dim ... as new ..." syntax.
  
Recent Bug fixes and changes:

Version 1.367.26xx: 	(2016)
        fixes for serial IO, fn midi and utf8 print
	added beta support for BLE/Bluetooth LE

Version 3.6.7(b2): 
        fixes for Intel 64-bit version
Version 3.6.7(b0): 
        beta port for Cocoa (OS X 10.7 and later) with threading
	removed PPC support
Version 3.6.6(b0):
	fixed a gosub error message
	changed document file type to .bas 'text'
	fixed graphic pict command
	fixed bugs in several mat commands
Version 3.6.5(b0):
	fixed bugs in exit while, empty edit and for statements
	cleaned up buttons on graphics cls
Version 3.6.4(b8):
	fixed problems with fn plot1, format$, string objects
	added command: graphics arc x,y,r,a1,a2
Version 3.6.4(b7): 
        fixed some mat command syntax omissions
        fixed a function subroutine return bug
        allow subroutines to return 1d and 2d mat arrays
        added beta test object arrays
Version 3.6.4(b6): 
        added  def local  to name local sub variables
  3.6.4(b5):
           allow restore command to use a labeled line
           added fn playsound() to play sound files
           fixed sound command for some multivoiced tones
           fixed graphics pict to work with more image files
           added fn eval()
           added #ifndef _chipmunkbasic_ to ignore code
           fixed documentation on 2 parameter atan()
  3.6.4(b1): allow larger bload/bsave file sizes
           added det() function to calculate 2d matrix determinants
           added fn dot(a,b) to calculate 1d vector dot product
           allow mat inv of larger matrices
           allow larger bload/bsave file sizes
           fixed some bugs in format$() and print using
           fixed default save button highlight in Mac Intel build
  3.6.3(b7): fixed socket read eof, object print
  3.6.3(b0): added dbm$ database commands
           fixed fn math$(), midi sound, macfunction "putstr2clip"
  3.6.2(b5): added fn system$(), version$, open pipe for output,
           fixed atn() bug, fixed Mac bundle name & icon
  3.6.1b3: fixed LET command for integer% variables
           documented fseek # command
  3.6.0b1: fixed serial port i/o problems, max graphics size problem,
           added external bundle support, added 44100 record option
  3.5.9b6: added graphics scrn to return pixel color
  3.5.9b5: fixed SFGetFile file path, line edit, def fn array params
           added te2cbas applescript
  3.5.9b3: fixed long if, instr(), mid$(), val("..") bugs
           added fn math$(), fn plot1(), fn solve1()
  3.5.9b2: OS X Carbon port, changed file paths, fixed SaveAs
           fixed fn record & sound playback
           fixed serial port access, sys(), sockets, pipes
  3.5.9b0: fixed format$() bug and International string compares
  3.5.8b4: fixed inkey$, changed int() to round towards -infinity
  
Older bug fixes and changes:
  3.3.5: fixed integer rounding
  3.3.7: fixed assignment to variable "this" in object methods fixed
  3.4.0: fixed default voice in say, input eof bug, pref file bug
  3.4.2: fixed hex$() of negative numbers
  3.4.5: fixed moveto & button clear
  3.4.7: fixed fixed nesting of if-then-else
  3.4.8: fixed nesting of select-case
  3.5.1: fixed some print using bugs, increased input line to 254 chars.
  3.5.2: added backup on save, fixed 68K stdio EOLN.
  3.5.3: fixed SFPutFile filename return, added for/next integer index's
  3.5.4: fixed while/wend exit bug, fixed ubound/isarray docs,
  3.5.5: fixed OTLib link bug  
  3.5.7: fixed integer array access bug
  3.5.8: fixed format$()
  			
Please send bug reports to  rhn AT nicholson DOT com

---
Thanks to:
 - Dave Gillespie for writing the original Pascal version of this Basic;
 - Dave Betz for ideas from the original XLisp 1.6 Mac console;
 - many folks from Apple DTS, Metrowerks, the c.s.m.p newsgroup, etc.;
 - Thomas Ferrell for contributing a tutorial for the web page;
 - & the many people who who have sent me polite detailed bug reports.
 - Mark Henderson & Paul Rouse forthe public domain fgmp bignum package.
 
 * Portions of this release of Chipmunk Basic are
 *   Copyright (c) 1983 Regents of the University of California.
 *   Copyright (c) 1993 Regents of the University of California.
 *   Copyright (c) 2000, 2005 Apple Computer, Inc.
 * Portions of Chipmunk Basic are Copyright (C) 1989 Dave Gillespie.
 
---
A  sample program:

--- cut here ---
1 rem "sieve.bas" , a prime number sieve benchmark
2 t = timer
3 dim f(8194)
4 for i = 0 to 8191 : f(i) = 1 : next i
5 s = 8191
6 for i = 0 to s
7   if f(i) = 0 then goto 11
8   p = i+i+3
9   for k = i+p to s step p : f(k) = 0 : next k
10   c = c+1
11 next i
12 print c;" primes found in ";
13 t = timer-t
14 print t;" seconds"
15 end
--- cut here ---
*/