Backport of 4f336f66523001b009ab038b10848508fd208b3b from master
Thanks Tim Graham for completing the initial patch.