Moved a lot of logic out of the service entry point and into a separate library.