Move more code for reuse in CLI tool