Cleaned up functions, added more comments and docstrings, improved readability.