Refactor to reduce some nested scopes