Backport of eb9b56c5b6 from master
eb9b56c5b6
Thanks Carl Meyer and Tim Graham for contributing to the patch.