WIP: rewrite the next-state logic