Bug fixes

See commit messages for details.