tweaked loop logic