Refactoring

Remove unused code
Fewer opens
Other light refactoring (merging functions, splitting modules).

Output is the same as current master, modulo whitespace.