Refactor to fix threading issues