Set main language for the given collection of cells, and
    use magics for cells that use other languages

def set_main_and_cell_language(metadata, cells, ext):
    """Set main language for the given collection of cells, and
    use magics for cells that use other languages"""
    main_language = (metadata.get('kernelspec', {}).get('language') or
                     metadata.get('jupytext', {}).get('main_language') or
                     _SCRIPT_EXTENSIONS.get(ext, {}).get('language'))

    if main_language is None:
        languages = {'python': 0.5}
        for cell in cells:
            if 'language' in cell['metadata']:
                language = cell['metadata']['language']
                languages[language] = languages.get(language, 0.0) + 1

        main_language = max(languages, key=languages.get)

    # save main language when no kernel is set
    if 'language' not in metadata.get('kernelspec', {}):
        metadata.setdefault('jupytext', {})['main_language'] = main_language

    # Remove 'language' meta data and add a magic if not main language
    for cell in cells:
        if 'language' in cell['metadata']:
            language = cell['metadata'].pop('language')
            if language != main_language and language in _JUPYTER_LANGUAGES:
                if 'magic_args' in cell['metadata']:
                    magic_args = cell['metadata'].pop('magic_args')
                    cell['source'] = u'%%{} {}\n'.format(language, magic_args) + cell['source']
                else:
                    cell['source'] = u'%%{}\n'.format(language) + cell['source']