Some major refactoring, added regression tests