attempting to refactor to improve complexity and readability.