refactoring and minor optimization