Refactor deepCopy function