cmake: Several fixes to the build system (rebased for 0.9.6)

PR #189, rebased for 0.9.6.

I'm not sure what your policy is for managing branches; maybe you do this automatically?  This is just the same as #189 but rebased onto 0.9.6.