main loop logic, cpp only