refactored, all tests passing