Refactor into routes, remove use of globals in non-tests