changed work with threads, and a little refactoring