consolidated looping logic