Changed for() loop to while()