Refactoring attempt.

An attempt to make this code a little less crap. Would still benefit from monads.

It's probably even worse than what I started with, but the idea may be reasonable.

I probably should start questioning my own sanity.