improved change_directory logic