Restructure main loop for better timing