Much better algorithm