Refactoring and sanitizing. Added docstring.