Rewrite main loop using function and exceptions