Modified to allow mainloop to be run iteratively.