Shuffle around some logic to make things a bit easier to understand