WIP: Refactor into functions.

Not sure I like this.