Lots of bugfixes.

The exact fixes are in the commits themselves.