Rewriten a bunch of code, added tests to create this package testable.