some refactoring and optimizations