Rewrite main.php for efficiency and correctness