Backport of 0ed7d15563 from master
0ed7d15563
Thanks Collin Anderson for the input when creating the patch and Tim Graham for the review.