fix infinite loop, but nested loop is not working