Explain a scenario where you had to refactor a legacy codebase, and how you ensured you did not introduce new bugs.