[rebase] fixes to make it work on mac os x 10.9 mavericks

This is a rebase of #343 with some of the reordering requested by @jspricke.