Refactor into a lib