Backport of 0ed7d155635da9f79d4dd67e4889087d3673c6da from master
Thanks to Russell Keith-Magee for mentoring this Google Summer of Code 2014 project and everyone else who helped with the patch!