General refactor, fixed deadlock