corrected cycles to actually working algorithm