A few optimizations and code refactoring