Some basic cleanup and refactoring so that I can use the internals of these functions elsewhere.