Major refactoring in prep for code reuse and extension.