major refactoring, much better now