Refactor partly for and add some unit tests