Slowly refactoring this into something better.
Finally refactored into a nicer layout, should be testable.