fix nested loop problem