Re-apply felixclack's pull request 227

I've re-applied felixclack's gh-227 with various changes to get the tests passing on my box.