Commiting functional but broken algorithm (it works well enough for the purpose, but I don't like the results.