rewrite the generator

to be simpler and fix a lot of trailing whitespace, bugs, bad output and other inconsistencies.