Bug fixes

See the commits for details.