improved logic in loop()