Refactor thread handling and reformat