FIX Bug caused by misuse of loop ending condition