refactor

- add comments
- robustify
- add better logging