Bug fixes

See commit messages for the details.