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