refactoring and fix for #1097