Moved most of the code out into its own file