First pass refactoring for understanding and cleanup.