Improve freeing of the state structure