Clean up implementation, fix some bugs, and add comments.