Fix ugliness of the code

This should be easier to read with less nesting