Basically a rewrite. Should be less awful this time.