Fixed a few bugs

See commit messages for details.