Refactor working code for readability and efficiency