Manually backport from master, commit 6dabf50 and its fixes. Original author Ivan Sorokin.