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