Code improvements and refactoring