finally fixed the loop bug