Fixed threading problem. This is a working version.