Refactored to make it easier to understand and modify.