optimizations and refactoring