Moved functions around to achieve thread persistence. Note that I have not tested yet, so this is likely to not work.