Fix 2498

There was a subtle problem in #2498 that broke the fix for #2495, this PR fixes it by refactoring the code, and there's a test this time. :-)