fix looping algorithm