Clean up source; add error checking and docstrings.