Main function finished

Hasn't been tested.
Fix some bugs