Move chdir() to where it is needed