Patch from Dmitry-Me: reorder checks so that cheaper ones go first, reuse previously computed values, return early on edge condition