Add a loop guard as suggested by jvennix-r7