Rewrite main logic