Misc bug fixes

Just a bunch of bug fixes accumulated over a few debugging sessions.