As this is a non-trivial function, a docstring or comment describing it would be really useful to the reader.