General fixes.

Please see the comments on individual commits.