Massive restructuring of main.cpp. Tidied up other files.