Move business logic out to library code

With tests, natch
Moved some stuff out of app.