Continued refactoring. Added some functions, and other cleanup.