Cleaning up the code. Put code in main into funcitons to make it more readable.