I had copy-pasted these functions to a few other places. Clean that up, move them to a common module, and add some comments.