added a safety stop in while loops