StateChange  function refactored