Main function

Yes I know, it needs commenting.