some refactoring and optimization