improved switch state code