Main loop refactor

Move all the main-loop related code into a single common file. main.cpp and main_nogui.cpp are now reduced to small consumers of the "common" library.