]> git.donarmstrong.com Git - lilypond.git/blobdiff - scripts/musicxml2ly.py
MusicXML: Cleanup of span start/end and direction, coding style
[lilypond.git] / scripts / musicxml2ly.py
index e3582682349ade26bacab3022af1c7c51b534567..c82e9ce5897176b3089349c91d877cdacec839d0 100644 (file)
@@ -24,12 +24,57 @@ def progress (str):
     sys.stderr.flush ()
     
 
+# score information is contained in the <work>, <identification> or <movement-title> tags
+# extract those into a hash, indexed by proper lilypond header attributes
+def extract_score_information (tree):
+    score_information = {}
+    def set_if_exists (field, value):
+        if value:
+            score_information[field] = value
+
+    work = tree.get_maybe_exist_named_child ('work')
+    if work:
+        set_if_exists ('title', work.get_work_title ())
+        set_if_exists ('worknumber', work.get_work_number ())
+        set_if_exists ('opus', work.get_opus ())
+    else:
+        movement_title = tree.get_maybe_exist_named_child ('movement-title')
+        if movement_title:
+            set_if_exists ('title', movement_title.get_text ())
+    
+    identifications = tree.get_named_children ('identification')
+    for ids in identifications:
+        set_if_exists ('copyright', ids.get_rights ())
+        set_if_exists ('composer', ids.get_composer ())
+        set_if_exists ('arranger', ids.get_arranger ())
+        set_if_exists ('editor', ids.get_editor ())
+        set_if_exists ('poet', ids.get_poet ())
+            
+        set_if_exists ('tagline', ids.get_encoding_software ())
+        set_if_exists ('encodingsoftware', ids.get_encoding_software ())
+        set_if_exists ('encodingdate', ids.get_encoding_date ())
+        set_if_exists ('encoder', ids.get_encoding_person ())
+        set_if_exists ('encodingdescription', ids.get_encoding_description ())
+
+    return score_information
+
+
+def print_ly_information (printer, score_information):
+    printer.dump ('\header {')
+    printer.newline ()
+    for (k, text) in score_information.items ():
+        printer.dump ('%s = %s' % (k, musicxml.escape_ly_output_string (text)))
+        printer.newline ()
+    printer.dump ('}')
+    printer.newline ()
+    printer.newline ()
+    
+
 def musicxml_duration_to_lily (mxl_note):
     d = musicexp.Duration ()
-    if mxl_note.get_maybe_exist_typed_child (musicxml.Type):
-        d.duration_log = mxl_note.get_duration_log ()
-    else:
-        d.duration_log = 0
+    # if the note has no Type child, then that method spits out a warning and 
+    # returns 0, i.e. a whole note
+    d.duration_log = mxl_note.get_duration_log ()
 
     d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
     d.factor = mxl_note._duration / d.get_length ()
@@ -49,7 +94,7 @@ def group_tuplets (music_list, events):
     j = 0
     for (ev_chord, tuplet_elt, fraction) in events:
         while (j < len (music_list)):
-            if music_list[j]== ev_chord:
+            if music_list[j] == ev_chord:
                 break
             j += 1
         if tuplet_elt.type == 'start':
@@ -82,7 +127,7 @@ def group_tuplets (music_list, events):
 
 def musicxml_clef_to_lily (attributes):
     change = musicexp.ClefChange ()
-    change.type = attributes.get_clef_sign ()
+    (change.type, change.position, change.octave) = attributes.get_clef_information ()
     return change
     
 def musicxml_time_to_lily (attributes):
@@ -131,10 +176,10 @@ def musicxml_attributes_to_lily (attrs):
         'key': musicxml_key_to_lily
     }
     for (k, func) in attr_dispatch.items ():
-        childs = attrs.get_named_children (k)
+        children = attrs.get_named_children (k)
 
         ## ugh: you get clefs spread over staves for piano
-        if childs:
+        if children:
             elts.append (func (attrs))
     
     return elts
@@ -142,10 +187,21 @@ def musicxml_attributes_to_lily (attrs):
 spanner_event_dict = {
     'slur' : musicexp.SlurEvent,
     'beam' : musicexp.BeamEvent,
-}        
+    'glissando' : musicexp.GlissandoEvent,
+    'pedal' : musicexp.PedalEvent,
+    'wavy-line' : musicexp.TrillSpanEvent,
+    'octave-shift' : musicexp.OctaveShiftEvent,
+    'wedge' : musicexp.HairpinEvent
+}
 spanner_type_dict = {
     'start': -1,
     'begin': -1,
+    'crescendo': -1,
+    'decreschendo': -1,
+    'diminuendo': -1,
+    'continue': 0,
+    'up': -1,
+    'down': -1,
     'stop': 1,
     'end' : 1
 }
@@ -154,27 +210,193 @@ def musicxml_spanner_to_lily_event (mxl_event):
     ev = None
     
     name = mxl_event.get_name()
-    try:
-        func = spanner_event_dict[name]
+    func = spanner_event_dict.get (name)
+    if func:
         ev = func()
-    except KeyError:
+    else:
         print 'unknown span event ', mxl_event
 
-    try:
-        key = mxl_event.get_type ()
-        ev.span_direction = spanner_type_dict[key]
-    except KeyError:
-        print 'unknown span type', key, 'for', name
 
+    type = mxl_event.get_type ()
+    span_direction = spanner_type_dict.get (type)
+    # really check for None, because some types will be translated to 0, which
+    # would otherwise also lead to the unknown span warning
+    if span_direction != None:
+        ev.span_direction = span_direction
+    else:
+        print 'unknown span type', type, 'for', name
+
+    ev.set_span_type (type)
+    ev.line_type = getattr (mxl_event, 'line-type', 'solid')
+
+    # assign the size, which is used for octave-shift, etc.
+    ev.size = mxl_event.get_size ()
+
+    return ev
+
+def musicxml_direction_to_indicator (direction):
+    return { "above": 1, "upright": 1, "below": -1, "downright": -1 }.get (direction, '')
+
+def musicxml_fermata_to_lily_event (mxl_event):
+    ev = musicexp.ArticulationEvent ()
+    ev.type = "fermata"
+    if hasattr (mxl_event, 'type'):
+      dir = musicxml_direction_to_indicator (mxl_event.type)
+      if dir:
+        ev.force_direction = dir
+    return ev
+
+def musicxml_tremolo_to_lily_event (mxl_event):
+    if mxl_event.get_name () != "tremolo": 
+        return
+    ev = musicexp.TremoloEvent ()
+    ev.bars = mxl_event.get_text ()
+    return ev
+
+def musicxml_bend_to_lily_event (mxl_event):
+    if mxl_event.get_name () != "bend":
+        return
+    ev = musicexp.BendEvent ()
+    ev.alter = mxl_event.bend_alter ()
+    return ev
+
+
+# TODO: Some translations are missing!
+short_articulations_dict = {
+  "staccato": ".",
+  "tenuto": "-",
+  "stopped": "+",
+  "staccatissimo": "|",
+  "accent": ">",
+  "strong-accent": "^",
+  #"portato": "_", # does not exist in MusicXML
+    #"fingering": "", # fingering is special cased, as get_text() will be the event's name
+}
+articulations_dict = { 
+    ##### ORNAMENTS
+    "trill-mark": "trill", 
+    "turn": "turn", 
+    #"delayed-turn": "?", 
+    "inverted-turn": "reverseturn", 
+    #"shake": "?", 
+    #"wavy-line": "?", 
+    "mordent": "mordent",
+    "inverted-mordent": "prall",
+    #"schleifer": "?" 
+    ##### TECHNICALS
+    "up-bow": "upbow", 
+    "down-bow": "downbow", 
+    "harmonic": "flageolet", 
+    #"open-string": "", 
+    #"thumb-position": "", 
+    #"pluck": "", 
+    #"double-tongue": "", 
+    #"triple-tongue": "", 
+    #"snap-pizzicato": "", 
+    #"fret": "", 
+    #"string": "", 
+    #"hammer-on": "", 
+    #"pull-off": "", 
+    #"bend": "bendAfter #%s", # bend is special-cased, as we need to process the bend-alter subelement!
+    #"tap": "", 
+    #"heel": "", 
+    #"toe": "", 
+    #"fingernails": ""
+    ##### ARTICULATIONS
+    #"detached-legato": "", 
+    #"spiccato": "", 
+    #"scoop": "", 
+    #"plop": "", 
+    #"doit": "", 
+    #"falloff": "",
+    "breath-mark": "breathe", 
+    #"caesura": "caesura", 
+    #"stress": "", 
+    #"unstress": ""
+}
+articulation_spanners = [ "wavy-line" ]
+
+def musicxml_articulation_to_lily_event (mxl_event):
+    # wavy-line elements are treated as trill spanners, not as articulation ornaments
+    if mxl_event.get_name () in articulation_spanners:
+        return musicxml_spanner_to_lily_event (mxl_event)
+
+    # special case, because of the bend-alter subelement
+    if mxl_event.get_name() == "bend":
+        return musicxml_bend_to_lily_event (mxl_event)
+
+    # If we can write a shorthand, use them!
+    if mxl_event.get_name() == "fingering":
+        ev = musicexp.ShortArticulationEvent ()
+        tp = mxl_event.get_text()
+    # In all other cases, use the dicts to translate the xml tag name to a proper lilypond command
+    elif short_articulations_dict.get (mxl_event.get_name ()):
+        ev = musicexp.ShortArticulationEvent ()
+        tp = short_articulations_dict.get (mxl_event.get_name ())
+    else:
+        ev = musicexp.ArticulationEvent ()
+        tp = articulations_dict.get (mxl_event.get_name ())
+
+    if not tp:
+        return
+    
+    ev.type = tp
+
+    # Some articulations use the type attribute, other the placement...
+    dir = None
+    if hasattr (mxl_event, 'type'):
+        dir = musicxml_direction_to_indicator (mxl_event.type)
+    if hasattr (mxl_event, 'placement'):
+        dir = musicxml_direction_to_indicator (mxl_event.placement)
+    # \breathe cannot have any direction modifier (^, _, -)!
+    if dir and tp != "breathe":
+        ev.force_direction = dir
     return ev
 
+
+def musicxml_dynamics_to_lily_event (dynentry):
+    dynamics_available = ( "p", "pp", "ppp", "pppp", "ppppp", "pppppp",
+        "f", "ff", "fff", "ffff", "fffff", "ffffff",
+        "mp", "mf", "sf", "sfp", "sfpp", "fp",
+        "rf", "rfz", "sfz", "sffz", "fz" )
+    if not dynentry.get_name() in dynamics_available:
+        return
+    event = musicexp.DynamicsEvent ()
+    event.type = dynentry.get_name ()
+    return event
+
+
+direction_spanners = [ 'octave-shift', 'pedal', 'wedge' ]
+
+def musicxml_direction_to_lily (n):
+    # TODO: Handle the <staff> element!
+    res = []
+    dirtype_children = []
+    for dt in n.get_typed_children (musicxml.DirType):
+        dirtype_children += dt.get_all_children ()
+
+    for entry in dirtype_children:
+        if entry.get_name () == "dynamics":
+            for dynentry in entry.get_all_children ():
+                ev = musicxml_dynamics_to_lily_event (dynentry)
+                if ev:
+                    res.append (ev)
+
+        # octave shifts. pedal marks, hairpins etc. are spanners:
+        if entry.get_name() in direction_spanners:
+            event = musicxml_spanner_to_lily_event (entry)
+            if event:
+                res.append (event)
+
+
+    return res
+
 instrument_drumtype_dict = {
     'Acoustic Snare Drum': 'acousticsnare',
     'Side Stick': 'sidestick',
     'Open Triangle': 'opentriangle',
     'Mute Triangle': 'mutetriangle',
-    'Tambourine': 'tambourine',
-    
+    'Tambourine': 'tambourine'
 }
 
 def musicxml_note_to_lily_main_event (n):
@@ -197,9 +419,10 @@ def musicxml_note_to_lily_main_event (n):
         event = musicexp.RestEvent()
     elif n.instrument_name:
         event = musicexp.NoteEvent ()
-        try:
-            event.drum_type = instrument_drumtype_dict[n.instrument_name]
-        except KeyError:
+        drum_type = instrument_drumtype_dict.get (n.instrument_name)
+        if drum_type:
+            event.drum_type = drum_type
+        else:
             n.message ("drum %s type unknow, please add to instrument_drumtype_dict" % n.instrument_name)
             event.drum_type = 'acousticsnare'
     
@@ -219,6 +442,7 @@ class NegativeSkip:
 class LilyPondVoiceBuilder:
     def __init__ (self):
         self.elements = []
+        self.pending_dynamics = []
         self.end_moment = Rational (0)
         self.begin_moment = Rational (0)
         self.pending_multibar = Rational (0)
@@ -245,6 +469,16 @@ class LilyPondVoiceBuilder:
         self.elements.append (music)
         self.begin_moment = self.end_moment
         self.end_moment = self.begin_moment + duration 
+        
+        # Insert all pending dynamics right after the note/rest:
+        if duration > Rational (0):
+            for d in self.pending_dynamics:
+                self.elements.append (d)
+            self.pending_dynamics = []
+
+    def add_dynamics (self, dynamic):
+        # store the dynamic item(s) until we encounter the next note/rest:
+        self.pending_dynamics.append (dynamic)
 
     def add_bar_check (self, number):
         b = musicexp.BarCheck ()
@@ -271,10 +505,19 @@ class LilyPondVoiceBuilder:
     def last_event_chord (self, starting_at):
 
         value = None
+
+        # if the position matches, find the last EventChord, do not cross a bar line!
+        at = len( self.elements ) - 1
+        while (at >= 0 and
+               not isinstance (self.elements[at], musicexp.EventChord) and
+               not isinstance (self.elements[at], musicexp.BarCheck)):
+            at -= 1
+
         if (self.elements
-            and isinstance (self.elements[-1], musicexp.EventChord)
+            and at >= 0
+            and isinstance (self.elements[at], musicexp.EventChord)
             and self.begin_moment == starting_at):
-            value = self.elements[-1]
+            value = self.elements[at]
         else:
             self.jumpto (starting_at)
             value = None
@@ -290,6 +533,10 @@ class LilyPondVoiceBuilder:
 def musicxml_voice_to_lily_voice (voice):
     tuplet_events = []
     modes_found = {}
+    lyrics = {}
+        
+    for k in voice.get_lyrics_numbers ():
+        lyrics[k] = []
 
     voice_builder = LilyPondVoiceBuilder()
 
@@ -297,6 +544,14 @@ def musicxml_voice_to_lily_voice (voice):
         if n.get_name () == 'forward':
             continue
 
+        if isinstance (n, musicxml.Direction):
+            for a in musicxml_direction_to_lily (n):
+                if a.wait_for_note ():
+                    voice_builder.add_dynamics (a)
+                else:
+                    voice_builder.add_music (a, 0)
+            continue
+        
         if not n.get_maybe_exist_named_child ('chord'):
             try:
                 voice_builder.jumpto (n._when)
@@ -336,11 +591,8 @@ def musicxml_voice_to_lily_voice (voice):
         
         main_event = musicxml_note_to_lily_main_event (n)
 
-        try:
-            if main_event.drum_type:
-                modes_found['drummode'] = True
-        except AttributeError:
-            pass
+        if hasattr (main_event, 'drum_type') and main_event.drum_type:
+            modes_found['drummode'] = True
 
 
         ev_chord = voice_builder.last_event_chord (n._when)
@@ -353,6 +605,12 @@ def musicxml_voice_to_lily_voice (voice):
         notations = n.get_maybe_exist_typed_child (musicxml.Notations)
         tuplet_event = None
         span_events = []
+        
+        # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
+        # +tied | +slur | +tuplet | glissando | slide | 
+        #    ornaments | technical | articulations | dynamics |
+        #    +fermata | arpeggiate | non-arpeggiate | 
+        #    accidental-mark | other-notation
         if notations:
             if notations.get_tuplet():
                 tuplet_event = notations.get_tuplet()
@@ -375,6 +633,76 @@ def musicxml_voice_to_lily_voice (voice):
             mxl_tie = notations.get_tie ()
             if mxl_tie and mxl_tie.type == 'start':
                 ev_chord.append (musicexp.TieEvent ())
+                
+            fermatas = notations.get_named_children ('fermata')
+            for a in fermatas:
+                ev = musicxml_fermata_to_lily_event (a)
+                if ev: 
+                    ev_chord.append (ev)
+
+            arpeggiate = notations.get_named_children ('arpeggiate')
+            for a in arpeggiate:
+                ev_chord.append (musicexp.ArpeggioEvent ())
+
+            glissandos = notations.get_named_children ('glissando')
+            for a in glissandos:
+                ev = musicxml_spanner_to_lily_event (a)
+                if ev:
+                    ev_chord.append (ev)
+                
+            # Articulations can contain the following child elements:
+            #         accent | strong-accent | staccato | tenuto |
+            #         detached-legato | staccatissimo | spiccato |
+            #         scoop | plop | doit | falloff | breath-mark | 
+            #         caesura | stress | unstress
+            # Technical can contain the following child elements:
+            #         up-bow | down-bow | harmonic | open-string |
+            #         thumb-position | fingering | pluck | double-tongue |
+            #         triple-tongue | stopped | snap-pizzicato | fret |
+            #         string | hammer-on | pull-off | bend | tap | heel |
+            #         toe | fingernails | other-technical
+            # Ornaments can contain the following child elements:
+            #         trill-mark | turn | delayed-turn | inverted-turn |
+            #         shake | wavy-line | mordent | inverted-mordent | 
+            #         schleifer | tremolo | other-ornament, accidental-mark
+            ornaments = notations.get_named_children ('ornaments')
+            for a in ornaments:
+                for ch in a.get_named_children ('tremolo'):
+                    ev = musicxml_tremolo_to_lily_event (ch)
+                    if ev: 
+                        ev_chord.append (ev)
+
+            ornaments += notations.get_named_children ('articulations')
+            ornaments += notations.get_named_children ('technical')
+
+            for a in ornaments:
+                for ch in a.get_all_children ():
+                    ev = musicxml_articulation_to_lily_event (ch)
+                    if ev: 
+                        ev_chord.append (ev)
+
+            dynamics = notations.get_named_children ('dynamics')
+            for a in dynamics:
+                for ch in a.get_all_children ():
+                    ev = musicxml_dynamics_to_lily_event (ch)
+                    if ev:
+                        ev_chord.append (ev)
+
+        # Extract the lyrics
+        note_lyrics_processed = []
+        note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
+        for l in note_lyrics_elements:
+            if l.get_number () < 0:
+                for k in lyrics.keys ():
+                    lyrics[k].append (l.lyric_to_text ())
+                    note_lyrics_processed.append (k)
+            else:
+                lyrics[l.number].append(l.lyric_to_text ())
+                note_lyrics_processed.append (l.number)
+        for lnr in lyrics.keys ():
+            if not lnr in note_lyrics_processed:
+                lyrics[lnr].append ("\skip4")
+
 
         mxl_beams = [b for b in n.get_named_children ('beam')
                      if (b.get_type () in ('begin', 'end')
@@ -397,7 +725,7 @@ def musicxml_voice_to_lily_voice (voice):
     
     ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
 
-    seq_music = musicexp.SequentialMusic()
+    seq_music = musicexp.SequentialMusic ()
 
     if 'drummode' in modes_found.keys ():
         ## \key <pitch> barfs in drummode.
@@ -405,7 +733,10 @@ def musicxml_voice_to_lily_voice (voice):
                     if not isinstance(e, musicexp.KeySignatureChange)]
     
     seq_music.elements = ly_voice
-
+    lyrics_dict = {}
+    for k in lyrics.keys ():
+        lyrics_dict[k] = musicexp.Lyrics ()
+        lyrics_dict[k].lyrics_syllables = lyrics[k]
     
     
     if len (modes_found) > 1:
@@ -418,17 +749,16 @@ def musicxml_voice_to_lily_voice (voice):
         v.mode = mode
         return_value = v
     
-    return return_value
+    return (return_value, lyrics_dict)
 
 
 def musicxml_id_to_lily (id):
-    digits = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
-              'nine', 'ten']
+    digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
+              'Six', 'Seven', 'Eight', 'Nine', 'Ten']
     
-    for dig in digits:
-        d = digits.index (dig) + 1
-        dig = dig[0].upper() + dig[1:]
-        id = re.sub ('%d' % d, dig, id)
+    for digit in digits:
+        d = digits.index (digit)
+        id = re.sub ('%d' % d, digit, id)
 
     id = re.sub  ('[^a-zA-Z]', 'X', id)
     return id
@@ -463,6 +793,7 @@ def get_all_voices (parts):
         part_ly_voices = {}
         for n, v in name_voice.items ():
             progress ("Converting to LilyPond expressions...")
+            # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
             part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
 
         all_ly_voices[p] = part_ly_voices
@@ -512,14 +843,28 @@ def music_xml_voice_name_to_lily_name (part, name):
     str = "Part%sVoice%s" % (part.id, name)
     return musicxml_id_to_lily (str) 
 
-def print_voice_definitions (printer, voices):
+def music_xml_lyrics_name_to_lily_name (part, name, lyricsnr):
+    str = "Part%sVoice%sLyrics%s" % (part.id, name, lyricsnr)
+    return musicxml_id_to_lily (str) 
+
+def print_voice_definitions (printer, part_list, voices):
+    part_dict={}
     for (part, nv_dict) in voices.items():
-        
-        for (name, (voice, mxlvoice)) in nv_dict.items ():
+        part_dict[part.id] = (part, nv_dict)
+
+    for part in part_list:
+        (part, nv_dict) = part_dict.get (part.id, (None, {}))
+        for (name, ((voice, lyrics), mxlvoice)) in nv_dict.items ():
             k = music_xml_voice_name_to_lily_name (part, name)
             printer.dump ('%s = ' % k)
             voice.print_ly (printer)
             printer.newline()
+            
+            for l in lyrics.keys ():
+                lname = music_xml_lyrics_name_to_lily_name (part, name, l)
+                printer.dump ('%s = ' %lname )
+                lyrics[l].print_ly (printer)
+                printer.newline()
 
             
 def uniq_list (l):
@@ -532,13 +877,13 @@ def print_score_setup (printer, part_list, voices):
     printer.newline ()
     for part_definition in part_list:
         part_name = part_definition.id
-        try:
-            part = part_dict[part_name]
-        except KeyError:
+        part = part_dict.get (part_name)
+        if not part:
             print 'unknown part in part-list:', part_name
             continue
 
-        nv_dict = voices[part]
+        # TODO: Apparently this is broken! There is always only one staff...
+        nv_dict = voices.get (part)
         staves = reduce (lambda x,y: x+ y,
                 [mxlvoice._staves.keys ()
                  for (v, mxlvoice) in nv_dict.values ()],
@@ -551,15 +896,23 @@ def print_score_setup (printer, part_list, voices):
             printer.newline ()
             
             for s in staves:
-                staff_voices = [music_xml_voice_name_to_lily_name (part, voice_name)
+                staff_voices = [(music_xml_voice_name_to_lily_name (part, voice_name), voice_name, v)
                         for (voice_name, (v, mxlvoice)) in nv_dict.items ()
                         if mxlvoice._start_staff == s]
                 
                 printer ('\\context Staff = "%s" << ' % s)
                 printer.newline ()
-                for v in staff_voices:
+                for (v, voice_name, (music, lyrics)) in staff_voices:
                     printer ('\\context Voice = "%s"  \\%s' % (v,v))
                     printer.newline ()
+                    
+                    # Assign the lyrics to that voice
+                    for l in lyrics.keys ():
+                        ll = music_xml_lyrics_name_to_lily_name (part, voice_name, l)
+                        printer ('\\new Lyrics \\lyricsto "%s" \\%s' % (v, ll))
+                        printer.newline()
+                        printer.newline()
+                    
                 printer ('>>')
                 printer.newline ()
                 
@@ -570,9 +923,16 @@ def print_score_setup (printer, part_list, voices):
             printer ('\\new Staff <<')
             printer.newline ()
             for (n,v) in nv_dict.items ():
+                ((music, lyrics), voice) = v
+                nn = music_xml_voice_name_to_lily_name (part, n) 
+                printer ('\\context Voice = "%s"  \\%s' % (nn,nn))
+
+                # Assign the lyrics to that voice
+                for l in lyrics.keys ():
+                    ll = music_xml_lyrics_name_to_lily_name (part, n, l)
+                    printer ('\\new Lyrics \\lyricsto "%s" \\%s' % (nn, ll))
+                    printer.newline()
 
-                n = music_xml_voice_name_to_lily_name (part, n) 
-                printer ('\\context Voice = "%s"  \\%s' % (n,n))
             printer ('>>')
             printer.newline ()
             
@@ -611,12 +971,16 @@ def convert (filename, options):
         mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
         part_list = mxl_pl.get_named_children ("score-part")
         
+    # score information is contained in the <work>, <identification> or <movement-title> tags
+    score_information = extract_score_information (tree)
     parts = tree.get_typed_children (musicxml.Part)
     voices = get_all_voices (parts)
 
     if not options.output_name:
         options.output_name = os.path.basename (filename) 
         options.output_name = os.path.splitext (options.output_name)[0]
+    elif re.match (".*\.ly", options.output_name):
+        options.output_name = os.path.splitext (options.output_name)[0]
 
 
     defs_ly_name = options.output_name + '-defs.ly'
@@ -627,7 +991,8 @@ def convert (filename, options):
     printer.set_file (open (defs_ly_name, 'w'))
 
     print_ly_preamble (printer, filename)
-    print_voice_definitions (printer, voices)
+    print_ly_information (printer, score_information)
+    print_voice_definitions (printer, part_list, voices)
     
     printer.close ()
     
@@ -636,12 +1001,22 @@ def convert (filename, options):
     printer = musicexp.Output_printer()
     printer.set_file (open (driver_ly_name, 'w'))
     print_ly_preamble (printer, filename)
-    printer.dump (r'\include "%s"' % defs_ly_name)
+    printer.dump (r'\include "%s"' % os.path.basename (defs_ly_name))
     print_score_setup (printer, part_list, voices)
     printer.newline ()
 
     return voices
 
+def get_existing_filename_with_extension (filename, ext):
+    if os.path.exists (filename):
+        return filename
+    newfilename = filename + ".xml"
+    if os.path.exists (newfilename):
+        return newfilename;
+    newfilename = filename + "xml"
+    if os.path.exists (newfilename):
+        return newfilename;
+    return ''
 
 def main ():
     opt_parser = option_parser()
@@ -650,8 +1025,13 @@ def main ():
     if not args:
         opt_parser.print_usage()
         sys.exit (2)
-
-    voices = convert (args[0], options)
+    
+    # Allow the user to leave out the .xml or xml on the filename
+    filename = get_existing_filename_with_extension (args[0], "xml")
+    if filename and os.path.exists (filename):
+        voices = convert (filename, options)
+    else:
+        progress ("Unable to find input file %s" % args[0])
 
 if __name__ == '__main__':
     main()