complete code rewrite