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