Added saving and restoring of state and ran Ruf's code cleanup.