refactoring and comments for clarity