Refactor

complete refactor

- added tests
- readable and much simpler code