This code really needs a rewrite