Move code into separate files to make tracking the states
easier. Fixes for unit tests.