Major refactoring... testing pending.