Refactored totalStops function to avoid global variables.