Misc bug fixes

See the diff for details.