Rewritten main logic