This mess really needs a scratch rewrite...