Refactor into classes, fix a bunch of bugs.