major refactoring to prepare for unit tests