Thread and SQL changes

Merging optimization branch.