restructure main loop and try-catch