Fix a few issues.

Fixes #5011 and #5002 .
We don't really use the cwd. But it might be a good idea to chdir() back.