Refactor and add integration tests