Implemented better threading code -- still in testing phase