halfway working but thread not exiting correctly