Some minor refactor and multithread issues fixing