Refactoring and some optimizations