Describe a time when you had to refactor a poorly written legacy codebase. How did you ensure system stability during the transition?