Refactor done, and some comments and docstrings added.