Thanks Kristof Claes for the initial patch. Backport of 88034c9938d92193d2104ecfe77999c69301dcc1 from master