big refactor.  should be no functional change.
added some comments!