lots of refactoring; some tests
complete merge