factored out loop body, fixed some todos