Tons of changes to support a programmatic interface.

Pretty buggy though, as I didn't get as far as I wanted this weekend...