Backport of f530b4fdfc2be3c2a0edcf38ebeb12bb5a4f0b83 from master.
Thanks Trey Hunner for cleaning the initial patch and Tim Graham for the review.