Simplify code - bail out early, vreak loops early, reorder checks and declarations

This removes numerous redundant actions by breaking loops early also reorders checks to make cheaper ones run first and moves declarations closer to where they are first used.