Refactor logic and statehistory