Bug fixes

See the commit messages for more details.