fixed save/restore state bug; cleaned up code