Comments and cleanup

Added lots of comments, improved debug logging, and cleaned up a few
bits. If this doesn't work, revert to commit 064f17a