Refactored toggle function.