Fix incorrect loop implementation