Describe a scenario where you had to refactor a legacy codebase. What steps did you take to ensure system stability during the transition?