fix forloop to while loop