Code refactoring and improvements