Added some if statements to stop infinite looping.