Major code refactoring, main loop.