Code refactoring and improvement