An improved version of PR #2584, fixes #2583