Fix issues found during review.

Code still needs a lot of cleanup and doc, but everything is working.