Major refactoring. Don't think anything is broken, but something probably is anyway.