move session-saving code to a dedicated function