Moved most of the logic to the engine.