Refactored code for undo and redo methods.