Fix bugs. Threads refactoring