more refactoring and fix issue #517