Fixing buggy loop