refactoring save_state into smaller functions