Refactor stateserver

This is a pull request into @MMavipc's branch, not master. As such, it's intended for review by him only.

You should also review PR #30 before this one, since it's merged in here.

This is a major refactor that cleans up a lot of garbage.
I suggest that you review the commits one at a time, not all at once. Each commit does only one thing, so the review should be much easier that way.