More mega-function refactoring. Only 400 lines to go :)