Cleanup code:

1. reorder checks so that cheaper ones go first
2. reuse previously computed values
3. return early on edge condition

I'm not completely sure the first change doesn't break anything.