Various improvements to the build system.

See the commit messages for a changelog.