refactoring state transition algorithm as function