Clean up code a bit and reduce nesting