Extract state management code into it's own file