Rewrite most of the code