Backport of b3a8c9dab8 from master
b3a8c9dab8
Thanks Tim Graham for the review and suggestions. d19109fd37 from master.
d19109fd37