Manually backport from master, commit 00e09435 and its fixes. Original author Bruno Barbieri.