fix some looping logic