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