Some major refactoring, add tests

Towards getting production-ready