added cleanup code, fixed thread halting issues