Refactoring, and lifting of this code. Still needs work.