functionized main loop