Moved directory change logic into a separate method.