Separated the state guarding and state changing code into two parts.