Algorithm has a minor bug.
Almost works correctly.