Refactored the toggle function.