Complete rewrite, working well