check wikipedia.org for the algorithm