Rewrite some awful code