Inspired by issue 6742, but solved in a different way.