Fixed threadlocal error and re-organized