refactoring

I've tried to clean up the code a little.  Common functions and variables have been moved to a new module `THT`, allowing the removal of a few lines of copypasta.

I haven't been able to test if this all still works as intended, so please be careful :)

I hope these changes will make it easier for you to maintain the code in the future.