Fixed a potential threading issue and improved cleaning/formatting