Major refactor. This should make it easier to maintain.