Manually apply an improved version of PR #2427