Taken from #4013 submitted by Robin Palotai (@robinp).
