def fix_from_imports(red):
    """
    Converts "from" style imports to not use "flask.ext".

    Handles (with or without parens or linebreaks):
    from flask.ext.foo import bam --> from flask_foo import bam
    from flask.ext.foo.bar import bam --> from flask_foo.bar import bam
    from flask.ext import foo --> import flask_foo as foo
    """
    from_imports = red.find_all("FromImport")
    for node in from_imports:
        modules = node.value

        if (len(modules) < 2 or
                modules[0].value != 'flask' or
                modules[1].value != 'ext'):
            continue

        if len(modules) >= 3:
            name_str = ''
            if len(node.targets) == 1:
                name = node.targets[0].target
                module = node.targets[0].value

                if (name and name != module):
                    name_str = '%s as %s' % (module, name)
                else:
                    name_str = module
            else:
                for target in node.targets:
                    name_str += target.value

                    if not target.next:
                        continue

                    if (target.type == 'name_as_name'
                            and target.next.type != 'right_parenthesis'):
                        name_str += ', '

            modules_str = '.'.join([i.value for i in modules[2:]])

            node.replace('from flask_%s import %s'
                         % (modules_str, name_str))

        elif len(modules) == 2:
            module = node.modules()[0]
            node.replace("import flask_%s as %s"
                         % (module, module))
    return red