Some more progress with the Main function. Still pretty nasty, this.