Rewrite, now substantially less wtf-inducing