Working directory fixes
Progress towards implementing #16228 (closed). This just cleans up the logic around much of the current working directory manipulation. Some of the commits on top of this branch might want to be moved to the topic which finishes off #16228 (closed).