restructure to make code more segregated

Fully functional, though one test related to garbage collection is failing.