Pull some of the logic out so it can be used as a module.