Fixing a bug on endless looping