Fix many exceptions in Mainfunction.