Refactor and clean up core code.