Added main_loop function, with some validation