More algorithm fixes - switch loop order