Refactor some deeply nested code