Reduce bitwise ops abuse, break loops earlier, return earlier, make cheaper checks run earlier

This reduces unneeded computations by making use of short-circuiting, breaking loops earlier, moving declarations closer to where they are needed.