updated thread handling and added checks to stop running