Major refactoring to encapsulate state.