performance optimizations and some refactoring