re-integrate #8560 using @fat's code from the comment on #8614