Add all tests, fixes and refactor