Main loop functionality