Refactored and commented for clarity and organization.