A main loop function.