Refactoring chdir(dirname(filename)) pattern