Moved some repetitive code into a function, cleaned up some unneeded comments/old debug statements, and completed part of the refactoring, which still has more to go.