Issue #8484 by tj, comments and refactor