finalized code with threading