Code cleanup and reorg, add comments.