Factored code and added a missing docstring.