Basic refactoring stuff.
Renamed some vars.
Moved some reused code into a function.