Librarify this mess a little.
Repackaged as library. Started working on test.