refactoring and small optimizations