Factor out code to lib