Thanks to Aron Podrigal for the initial patch and Tim for the review. Backport of 65e005f8cd9c656e558e53e6c8b890cd0fcc9e74 from master
Thanks Russell Keith-Magee and Tim Graham for reviews.