Made full-working algorithm.