Update: Here is the code we currently use, abstracted into a helper function with lots of comments but it's really just two lines: