Fixed while loop bug in code