partial refactoring. some tests working, others almost.