Oh, a docstring would be great here, it's doing a lot in one function.