Total rewrite, much simpler now