This is a simplified version of b15ac9fb7b9dab50da6f264889bc530ac18d0e51 (see comment in the commit).