A much more clear implementation resulting from working with Amir and Trevor