def mealy2scxml(mealy):
    """Convert Mealy machine to SCXML.

    Using examples/transys/machine_examples:

    >>> from machine_examples import garage_counter
    >>> from tulip.transys.export import machine2scxml
    >>> m = garage_counter()
    >>> s = machine2scxml.mealy2scxml(m)
    >>> f = open('mealy.scxml', 'w')
    >>> f.write(s)
    >>> f.close()

    See Also
    ========
    transys.machines.mealy

    @param mealy: machine to export as SCXML
    @type mealy: MealyMachine

    @rtype: SCXML str
    """
    def indent(n):
        return '\n' +n*'\t'

    def transitions_str(from_state, mealy):
        s = ''
        trans = mealy.transitions.find([from_state] )
        n = 2

        for (from_state_, to_state, sublabel_dict) in trans:
            s += indent(n) +'<transition '
            n = n +1
            s += indent(n) +'event="input_present" '
            s += indent(n) +'cond="' +str(sublabel_dict) +'" '
            s += indent(n) +'target="' +str(to_state) +'"/>'
            n = n -1
            s += indent(n) +'</transition>'
        return s

    s = '<?xml version="1.0" encoding="UTF-8"?>\n'
    s += '<scxml xmlns="http://www.w3.org/2005/07/scxml" '
    s += ' version="1.0" '

    if len(mealy.states.initial) != 1:
        msg = 'Must have exactly 1 initial state.\n'
        msg += 'Got instead:\n\t' +str(mealy.states.initial() )
        raise Exception(msg)

    initial_state = mealy.states.initial()[0]
    s += 'initial="' +str(initial_state) +'">\n'

    for state in mealy.states():
        s += '\t<state id="' +str(state) +'">'
        s += transitions_str(state, mealy) +'\n'
        s += '\t</state>\n'

    s += '</scxml>'
    return s