Factor out state handling

This is to prepare the separation between client and server.
Rename a couple of things