updated looping logic