A bunch of bugfixes

No functional changes, only bugfixes.