refactoring, and some new functionality