Cleaned up further. Now using a state monad.