Refactoring code. Fixes #1388 and #1346.
Commit work-in-progress changes.
Merge branch 'feature1388'.

Fixes: #1388 and #1346.