rewrite most of the original code