Complete restructure / rewrite

This makes the code less embarassing - this is a much more maintainable
structure. Still needs cleanup, but this makes that possible.