Added docstrings and fixed error handling.