A lot of refactoring and bugg fixes in order to keep the session state.