Fix serious memory leak, move heavy lifting to thread.