Optimizations & some refactoring