Preliminary factoring

Use StringBuilder for optimization, also started some basic refactoring.