a lot of refactoring

Tests are running now. Starting to think that I should build something
from scratch instead.