Refactor some code

see the commits