Code is quite complex for this problem.

You don't have to use local booleans, but I find that it's easier to
follow.  However, the checks can be confusing