Refactored the code a little.
Added a few fixes to thec code that handles threads.
More simple fixes.