Complete rewrite, now it works