Massive refactor of tbgen.py