lots of refactoring, plus some new sample code