improve messaging system, clean up main loop code