Added docstrings, comments and tidied up