updated version with threading