Rewrite using modified version of state monad