Improve modularization and finally extract to lib