clean up and modularization of some functionality; TODO: add test suite