reduce code duplication, better handle cwd changes