Major refactor for thread safety