Rearranged while loop

Rearranged the while loop function and added a couple more conditionals.