refactored, fixed mem leaks. data is freed within thread