Python 3 port (and a bug I discovered on the way)

Unfinished, but feel free to merge this preliminary stuff.