Moved most of the code to an async thread.