clean and improve main loop