fixed faulty while loop