Issue #2297989 by fgm: general refactoring and cleanup.