Took me a couple minutes to figure out how this function works, maybe add some comments