def METHOD_NAME(xml, out_dir):
    lang_file = open(os.path.join(out_dir, COUNTRY_LANGUAGES_FILENAME), 'w')
    lang_writer = csv.writer(lang_file, delimiter='\t')
    def get_population_pct(lang):
        return int(lang.attrib.get('populationPercent', 0))
    lang_scripts = {}
    for lang in xml.xpath('//languageData/language'):
        language_code = lang.attrib['type'].lower()
        scripts = lang.get('scripts')
        if not scripts:
            continue
        territories = lang.get('territories')
        if (language_code, None) not in lang_scripts:
            lang_scripts[(language_code, None)] = scripts
        if not territories:
            continue
        for territory in territories.strip().split():
            lang_scripts[(language_code, territory.lower())] = scripts
    for territory in xml.xpath('//territoryInfo/territory'):
        country_code = territory.attrib['type'].lower()
        if country_code == UNKNOWN_COUNTRY:
            continue
        langs = territory.xpath('languagePopulation')
        languages = Counter()
        official = set()
        regional = set()
        for lang in langs:
            language = lang.attrib['type'].lower().split('_')[0]
            official_status = lang.attrib.get('officialStatus')
            languages[language] += float(lang.attrib['populationPercent'])
            if official_status and official_status != REGIONAL:
                official.add(language)
            elif official_status == REGIONAL:
                regional.add(language)
        if official:
            languages = Counter({l: c for l, c in languages.iteritems()
                                 if l in official or l in regional})
        else:
            languages = Counter({l: c for l, c in languages.most_common(1)})
        for lang, pct in languages.most_common():
            if lang in UNKNOWN_LANGUAGES:
                continue
            script = lang_scripts.get((lang, country_code), lang_scripts.get((lang, None), ''))
            lang_writer.writerow((country_code, lang, script.replace(' ', ','),
                                  str(min(pct, 100.0)), str(int(lang in official))))