Thanks Reinout van Rees for contributing to the patch. Backport of 98bcc5d81bca578f3a5b4d47907ba4ac40446887 from master