speed optimizations and refactoring