Code cleanup

* switch'd to an output bufferr
* switch'd to use sets
* rework code to reduce work done in loops and clean it up