Massive code cleanup

Converted the two largest chunks of code into a function.