major refactoring and bug hunt
Clean up and added testbed