Implementing the main loop