Completely refactored with a much better algorithm