import re


def element_factory(selection, elType='radio', comment='', attrs=None):
    """Return an xml v2-Element as a list of strings

    Args:
        selection (list): Lines of text to be processed
    Kwargs:
        elType  (string): The name of the main xml element. e.g. `radio`
        comment (string): Text to be used in the comment cell
        attrs     (dict): Attributes to be added to the main xml element
    Return:
        list. List of strings making up the formatted v2-Element
    """
    attrs = {} if attrs is None else attrs
    selection = [line.rstrip() for line in selection if line.strip()]
    firstLine = selection.pop(0).strip()
    selection = '\n'.join(selection) if selection else ''

    try:
        label, title = firstLine.split(' ', 1)
    except ValueError:
        raise Exception("Question should be in format: Q1 Title")

    if label[0].isdigit():
        label = 'Q' + label

    # remove possible label delimiters
    label = re.sub(r'(\.$|[\(\):])', '', label)

    # dashes and periods become underscores
    label = re.sub(r'[-\.]', '_', label)

    template = '\n'.join(("<%(elType)s label=\"%(label)s\">",
                          "  <title>%(title)s</title>",
                          "%(selection)s",
                          "</%(elType)s>",
                          "<suspend/>"))

    if selection.find("<comment") == -1:
        selection = "  <comment>%s</comment>\n" % comment + selection

    element = (template % (dict(elType=elType,
                                label=label,
                                title=title,
                                selection=selection))).split("\n")

    attrs_str = " ".join('%s="%s"' % (k, v) for k, v in attrs.items())

    if attrs_str:
        element[0] = element[0].replace('">', '" ' + attrs_str + ">", 1)

    return element