First cleanup pass of shifting stuff to a header file and cleaning up the code