Thanks Adam Chidlow for polishing the patch. Backport of 03049fb8d9 from master
03049fb8d9
Thanks Anssi Kääriäinen for contributing to the patch.