Move state transition code to separate function