Refactoring attempt.

An attempt to make this code a little less crap. Still would benefit from a monad – the reader monad – though.

It's probably even worse than what I started with, but the idea may be reasonable.