patchset from Scrutinizer, tweaked by me