Added unitests, and more work on the logic