Major code refactoring to make it work with the app factory pattern