fixed an issue with threading, improved code