Added docstrings, comments, and assertions throughout.