Extended main loop to properly handle user input