Refactor to narrow the scope within which I/O calls are made.