Refactoring to remove duplicate code

Also move around some files to attempt to clean up the main directory.