some optimizations and refactoring