Thanks Simon Meers for the original patch. Backport of f97bbad908df128189eff77d98af9a25ed1ecf23 from master