Switching from State Monad to IORefs, minor code reorganization