Next batch of refactoring. Now with test cases. Still non-working state