]> git.donarmstrong.com Git - lilypond.git/blob - scripts/etf2ly.py
Merge with master
[lilypond.git] / scripts / etf2ly.py
1 #!@TARGET_PYTHON@
2
3 # info mostly taken from looking at files. See also
4 # http://lilypond.org/wiki/?EnigmaTransportFormat
5
6 # This supports
7 #
8 #  * notes
9 #  * rests
10 #  * ties
11 #  * slurs
12 #  * lyrics
13 #  * articulation
14 #  * grace notes
15 #  * tuplets
16 #
17
18 # todo:
19 #  * slur/stem directions
20 #  * voices (2nd half of frame?)
21 #  * more intelligent lyrics
22 #  * beams (better use autobeam?)
23 #  * more robust: try entertainer.etf (freenote)
24 #  * dynamics
25 #  * empty measures (eg. twopt03.etf from freenote)
26 #
27
28
29 import __main__
30 import getopt
31 import sys
32 import re
33 import string
34 import os
35
36 program_name = sys.argv[0]
37
38 version = '@TOPLEVEL_VERSION@'
39 if version == '@' + 'TOPLEVEL_VERSION' + '@':
40     version = '(unknown version)'           # uGUHGUHGHGUGH
41
42
43 ################################################################
44 # Users of python modules should include this snippet.
45 #
46
47
48
49
50 for d in ['@lilypond_datadir@',
51           '@lilypond_libdir@']:
52     sys.path.insert (0, os.path.join (d, 'python'))
53
54
55 # dynamic relocation, for GUB binaries.
56 bindir = os.path.abspath (os.path.split (sys.argv[0])[0])
57 for p in ['share', 'lib']:
58     datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % p)
59     sys.path.insert (0, datadir)
60
61
62 ################################################################
63
64 import lilylib as ly
65 _ = ly._
66  
67 finale_clefs= ['treble', 'alto', 'tenor', 'bass', 'percussion', 'treble_8', 'bass_8', 'baritone']
68
69 def lily_clef (fin):
70     try:
71         return finale_clefs[fin]
72     except IndexError:
73         sys.stderr.write ( '\nHuh? Found clef number %d\n' % fin)
74
75     return 'treble'
76     
77     
78
79 def gulp_file(f):
80     return open (f).read ()
81
82 # notename 0 == central C
83 distances = [0, 2, 4, 5, 7, 9, 11, 12]
84 def semitones (name, acc):
85     return (name / 7 ) * 12 + distances[name % 7] + acc
86
87 # represent pitches as (notename, alteration), relative to C-major scale
88 def transpose(orig, delta):
89     (oname, oacc) = orig
90     (dname, dacc) = delta
91     
92     old_pitch =semitones (oname, oacc)
93     delta_pitch = semitones (dname, dacc)
94     nname = (oname + dname) 
95     nacc = oacc
96     new_pitch = semitones (nname, nacc) 
97
98     nacc = nacc - (new_pitch - old_pitch - delta_pitch)
99
100     return (nname, nacc)
101
102
103
104 def interpret_finale_key_sig (finale_id):
105     """
106 find the transposition of C-major scale that belongs here.
107
108 we are not going to insert the correct major/minor, we only want to
109 have the correct number of accidentals
110 """
111
112     p = (0,0)
113
114     
115     bank_number = finale_id >> 8
116     accidental_bits = finale_id & 0xff
117
118     if 0 <= accidental_bits < 7:
119         while accidental_bits > 0:
120             p = transpose (p, (4,0)) # a fifth up
121             accidental_bits = accidental_bits - 1
122     elif 248 < accidental_bits <= 255:
123         while accidental_bits < 256:
124             p = transpose (p, (3,0))
125             accidental_bits = accidental_bits + 1
126
127     if bank_number == 1:
128         # minor scale
129         p = transpose (p, (5, 0))
130     p  = (p[0] % 7, p[1])
131
132     return KeySignature (p, bank_number)
133
134 # should cache this.
135 def find_scale (keysig):
136     cscale = map (lambda x: (x,0), range (0,7))
137 #        print "cscale: ", cscale
138     ascale = map (lambda x: (x,0), range (-2,5))
139 #        print "ascale: ", ascale
140     transposition = keysig.pitch
141     if keysig.sig_type == 1:
142         transposition = transpose(transposition, (2, -1))
143         transposition = (transposition[0] % 7, transposition[1])
144         trscale = map(lambda x, k=transposition: transpose(x, k), ascale)
145     else:
146         trscale = map(lambda x, k=transposition: transpose(x, k), cscale)
147 #        print "trscale: ", trscale
148     return trscale
149
150 def EDU_to_duration (edu):
151     log = 1
152     d = 4096
153     while d > edu:
154         d = d >> 1
155         log = log << 1
156
157     edu = edu - d
158     dots = 0
159     if edu == d /2:
160         dots = 1
161     elif edu == d*3/4:
162         dots = 2
163     return (log, dots)        
164
165 def rational_to_lily_skip (rat):
166     (n,d) = rat
167
168     basedur = 1
169     while d and  d % 2 == 0:
170         basedur = basedur << 1
171         d = d >> 1
172
173     str = 's%d' % basedur
174     if n <> 1:
175         str = str + '*%d' % n
176     if d <> 1:
177         str = str + '/%d' % d
178
179     return str
180
181 def gcd (a,b):
182     if b == 0:
183         return a
184     c = a
185     while c: 
186         c = a % b
187         a = b
188         b = c
189     return a
190     
191
192 def rat_simplify (r):
193     (n,d) = r
194     if d < 0:
195         d = -d
196         n = -n
197     if n == 0:
198         return (0,1)
199     else:
200         g = gcd (n, d)
201         return (n/g, d/g)
202     
203 def rat_multiply (a,b):
204     (x,y) = a
205     (p,q) = b
206
207     return rat_simplify ((x*p, y*q))
208
209 def rat_add (a,b):
210     (x,y) = a
211     (p,q) = b
212
213     return rat_simplify ((x*q + p*y, y*q))
214
215 def rat_neg (a):
216     (p,q) = a
217     return (-p,q)
218
219
220
221 def rat_subtract (a,b ):
222     return rat_add (a, rat_neg (b))
223
224 def lily_notename (tuple2):
225     (n, a) = tuple2
226     nn = chr ((n+ 2)%7 + ord ('a'))
227
228     return nn + {-2:'eses', -1:'es', 0:'', 1:'is', 2:'isis'}[a]
229
230
231 class Tuplet:
232     def __init__ (self, number):
233         self.start_note = number
234         self.finale = []
235
236     def append_finale (self, fin):
237         self.finale.append (fin)
238
239     def factor (self):
240         n = self.finale[0][2]*self.finale[0][3]
241         d = self.finale[0][0]*self.finale[0][1]
242         return rat_simplify( (n, d))
243     
244     def dump_start (self):
245         return '\\times %d/%d { ' % self.factor ()
246     
247     def dump_end (self):
248         return ' }'
249
250     def calculate (self, chords):
251         edu_left = self.finale[0][0] * self.finale[0][1]
252
253         startch = chords[self.start_note]
254         c = startch
255         while c and edu_left:
256             c.tuplet = self
257             if c == startch:
258                 c.chord_prefix = self.dump_start () + c.chord_prefix 
259
260             if not c.grace:
261                 edu_left = edu_left - c.EDU_duration ()
262             if edu_left == 0:
263                 c.chord_suffix = c.chord_suffix+ self.dump_end ()
264             c = c.next
265
266         if edu_left:
267             sys.stderr.write ("\nHuh? Tuplet starting at entry %d was too short." % self.start_note)
268         
269 class Slur:
270     def __init__ (self, number, params):
271         self.number = number
272         self.finale = params
273
274     def append_entry (self, finale_e):
275         self.finale.append (finale_e)
276
277     def calculate (self, chords):
278         startnote = self.finale[5]
279         endnote = self.finale[3*6 + 2]
280         try:
281             cs = chords[startnote]
282             ce = chords[endnote]
283
284             if not cs or not ce:
285                 raise IndexError
286             
287             cs.note_suffix = '-(' + cs.note_suffix 
288             ce.note_suffix = ce.note_suffix + '-)'
289             
290         except IndexError:
291             sys.stderr.write ("""\nHuh? Slur no %d between (%d,%d), with %d notes""" % (self.number,  startnote, endnote, len (chords)))
292                     
293         
294 class Global_measure:
295     def __init__ (self, number):
296         self.timesig = ''
297         self.number = number
298         self.key_signature = None
299         self.scale = None
300         self.force_break = 0
301         
302         self.repeats = []
303         self.finale = []
304
305     def __str__ (self):
306         return `self.finale `
307     
308     def set_timesig (self, finale):
309         (beats, fdur) = finale
310         (log, dots) = EDU_to_duration (fdur)
311
312         if dots == 1:
313             beats = beats * 3
314             log = log * 2
315             dots = 0
316
317         if dots <> 0:
318             sys.stderr.write ("\nHuh? Beat duration has  dots? (EDU Duration = %d)" % fdur) 
319         self.timesig = (beats, log)
320
321     def length (self):
322         return self.timesig
323     
324     def set_key_sig (self, finale):
325         k = interpret_finale_key_sig (finale)
326         self.key_signature = k
327         self.scale = find_scale (k)
328
329     def set_flags (self,flag1, flag2):
330         
331         # flag1 isn't all that interesting.
332         if flag2 & 0x8000:
333             self.force_break = 1
334             
335         if flag2 & 0x0008:
336             self.repeats.append ('start')
337         if flag2 & 0x0004:
338             self.repeats.append ('stop')
339             
340         if flag2 & 0x0002:
341             if flag2 & 0x0004:
342                 self.repeats.append ('bracket')
343
344 articulation_dict ={
345     94: '^',
346     109: '\\prall',
347     84: '\\turn',
348     62: '\\mordent',
349     85: '\\fermata',
350     46: '.',
351 #        3: '>',
352 #        18: '\arpeggio' ,
353 }
354
355 class Articulation_def:
356     def __init__ (self, n, a, b):
357         self.finale_glyph = a & 0xff
358         self.number = n
359
360     def dump (self):
361         try:
362             return articulation_dict[self.finale_glyph]
363         except KeyError:
364             sys.stderr.write ("\nUnknown articulation no. %d" % self.finale_glyph)
365             sys.stderr.write ("\nPlease add an entry to articulation_dict in the Python source")                        
366             return None
367     
368 class Articulation:
369     def __init__ (self, a,b, finale):
370         self.definition = finale[0]
371         self.notenumber = b
372         
373     def calculate (self, chords, defs):
374         c = chords[self.notenumber]
375
376         adef = defs[self.definition]
377         lystr =adef.dump()
378         if lystr == None:
379             lystr = '"art"'
380             sys.stderr.write ("\nThis happened on note %d" % self.notenumber)
381
382         c.note_suffix = '-' + lystr
383
384 class Syllable:
385     def __init__ (self, a,b , finale):
386         self.chordnum = b
387         self.syllable = finale[1]
388         self.verse = finale[0]
389     def calculate (self, chords, lyrics):
390         self.chord = chords[self.chordnum]
391
392 class Verse:
393     def __init__ (self, number, body):
394         self.body = body
395         self.number = number
396         self.split_syllables ()
397     def split_syllables (self):
398         ss = re.split ('(-| +)', self.body)
399
400         sep = 0
401         syls = [None]
402         for s in ss:
403             if sep:
404                 septor = re.sub (" +", "", s)
405                 septor = re.sub ("-", " -- ", septor) 
406                 syls[-1] = syls[-1] + septor
407             else:
408                 syls.append (s)
409             
410             sep = not sep 
411
412         self.syllables = syls
413
414     def dump (self):
415         str = ''
416         line = ''
417         for s in self.syllables[1:]:
418             line = line + ' ' + s
419             if len (line) > 72:
420                 str = str + ' ' * 4 + line + '\n'
421                 line = ''
422             
423         str = """\nverse%s = \\lyricmode {\n %s }\n""" %  (encodeint (self.number - 1) ,str)
424         return str
425
426 class KeySignature:
427     def __init__(self, pitch, sig_type = 0):
428         self.pitch = pitch
429         self.sig_type = sig_type
430     
431     def signature_type (self):
432         if self.sig_type == 1:
433             return "\\minor"
434         else:
435             # really only for 0, but we only know about 0 and 1
436             return "\\major"
437     
438     def equal (self, other):
439         if other and other.pitch == self.pitch and other.sig_type == self.sig_type:
440             return 1
441         else:
442             return 0
443     
444
445 class Measure:
446     def __init__(self, no):
447         self.number = no
448         self.frames = [0] * 4
449         self.flags = 0
450         self.clef = 0
451         self.finale = []
452         self.global_measure = None
453         self.staff = None
454         self.valid = 1
455         
456
457     def valid (self):
458         return self.valid
459     def calculate (self):
460         fs = []
461
462         if len (self.finale) < 2:
463             fs = self.finale[0]
464
465             self.clef = fs[1]
466             self.frames = [fs[0]]
467         else:
468             fs = self.finale
469             self.clef = fs[0]
470             self.flags = fs[1]
471             self.frames = fs[2:]
472
473
474 class Frame:
475     def __init__ (self, finale):
476         self.measure = None
477         self.finale = finale
478         (number, start, end ) = finale
479         self.number = number
480         self.start = start
481         self.end = end
482         self.chords  = []
483
484     def set_measure (self, m):
485         self.measure = m
486
487     def calculate (self):
488
489         # do grace notes.
490         lastch = None
491         in_grace = 0
492         for c in self.chords:
493             if c.grace and (lastch == None or (not lastch.grace)):
494                 c.chord_prefix = r'\grace {' + c.chord_prefix
495                 in_grace = 1
496             elif not c.grace and lastch and lastch.grace:
497                 lastch.chord_suffix = lastch.chord_suffix + ' } '
498                 in_grace = 0
499                 
500             lastch = c
501
502         if lastch and in_grace:
503             lastch.chord_suffix += '}' 
504
505         
506     def dump (self):
507         str = '%% FR(%d)\n' % self.number
508         left = self.measure.global_measure.length ()
509
510         
511         ln = ''
512         for c in self.chords:
513             add = c.ly_string () + ' '
514             if len (ln) + len(add) > 72:
515                 str = str + ln + '\n'
516                 ln = ''
517             ln = ln + add
518             left = rat_subtract (left, c.length ())
519
520         str = str + ln 
521         
522         if left[0] < 0:
523             sys.stderr.write ("""\nHuh? Going backwards in frame no %d, start/end (%d,%d)""" % (self.number, self.start, self.end))
524             left = (0,1)
525         if left[0]:
526             str = str + rational_to_lily_skip (left)
527
528         str = str + '  | \n'
529         return str
530         
531 def encodeint (i):
532     return chr ( i  + ord ('A'))
533
534 class Staff:
535     def __init__ (self, number):
536         self.number = number
537         self.measures = []
538
539     def get_measure (self, no):
540         fill_list_to (self.measures, no)
541
542         if self.measures[no] == None:
543             m = Measure (no)
544             self.measures [no] =m
545             m.staff = self
546
547         return self.measures[no]
548     def staffid (self):
549         return 'staff' + encodeint (self.number - 1)
550     def layerid (self, l):
551         return self.staffid() +  'layer%s' % chr (l -1 + ord ('A'))
552     
553     def dump_time_key_sigs (self):
554         k  = ''
555         last_key = None
556         last_time = None
557         last_clef = None
558         gap = (0,1)
559         for m in self.measures[1:]:
560             if not m or not m.valid:
561                 continue # ugh.
562             
563             g = m.global_measure
564             e = ''
565             
566             if g:
567                 if g.key_signature and not g.key_signature.equal(last_key):
568                     pitch= g.key_signature.pitch
569                     e = e + "\\key %s %s " % (lily_notename (pitch),
570                                  g.key_signature.signature_type())
571                     
572                     last_key = g.key_signature
573                 if last_time <> g.timesig :
574                     e = e + "\\time %d/%d " % g.timesig
575                     last_time = g.timesig
576
577                 if 'start' in g.repeats:
578                     e = e + ' \\bar "|:" ' 
579
580
581                 # we don't attempt voltas since they fail easily.
582                 if 0 : # and g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket:
583                     strs = []
584                     if g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket == 'end':
585                         strs.append ('#f')
586
587                     
588                     if g.bracket == 'start':
589                         strs.append ('"0."')
590
591                     str = string.join (map (lambda x: '(volta %s)' % x, strs))
592                     
593                     e = e + ' \\set Score.repeatCommands =  #\'(%s) ' % str
594
595                 if g.force_break:
596                     e = e + ' \\break '  
597             
598             if last_clef <> m.clef :
599                 e = e + '\\clef "%s"' % lily_clef (m.clef)
600                 last_clef = m.clef
601             if e:
602                 if gap <> (0,1):
603                     k = k +' ' + rational_to_lily_skip (gap) + '\n'
604                 gap = (0,1)
605                 k = k + e
606                 
607             if g:
608                 gap = rat_add (gap, g.length ())
609                 if 'stop' in g.repeats:
610                     k = k + ' \\bar ":|" '
611                 
612         k = '%sglobal = { %s }\n\n ' % (self.staffid (), k)
613         return k
614     
615     def dump (self):
616         str = ''
617
618
619         layerids = []
620         for x in range (1,5): # 4 layers.
621             laystr =  ''
622             last_frame = None
623             first_frame = None
624             gap = (0,1)
625             for m in self.measures[1:]:
626                 if not m or not m.valid:
627                     sys.stderr.write ("Skipping non-existant or invalid measure\n")
628                     continue
629
630                 fr = None
631                 try:
632                     fr = m.frames[x]
633                 except IndexError:
634                     sys.stderr.write ("Skipping nonexistent frame %d\n" % x)
635                     laystr = laystr + "%% non existent frame %d (skipped) \n" % x
636                 if fr:
637                     first_frame = fr
638                     if gap <> (0,1):
639                         laystr = laystr +'} %s {\n ' % rational_to_lily_skip (gap)
640                         gap = (0,1)
641                     laystr = laystr + fr.dump ()
642                 else:
643                     if m.global_measure :
644                         gap = rat_add (gap, m.global_measure.length ())
645                     else:
646                         sys.stderr.write ( \
647                             "No global measure for staff %d measure %d\n"
648                             % (self.number, m.number))
649             if first_frame:
650                 l = self.layerid (x)
651                 laystr = '%s = { {  %s } }\n\n' % (l, laystr)
652                 str = str  + laystr
653                 layerids.append (l)
654
655         str = str +  self.dump_time_key_sigs ()                
656         stafdef = '\\%sglobal' % self.staffid ()
657         for i in layerids:
658             stafdef = stafdef + ' \\' + i
659             
660
661         str = str + '%s = \\context Staff = %s <<\n %s\n >>\n' % \
662            (self.staffid (), self.staffid (), stafdef)
663         return str
664
665                 
666
667 def ziplist (l):
668     if len (l) < 2:
669         return []
670     else:
671         return [(l[0], l[1])] + ziplist (l[2:])
672
673
674 class Chord:
675     def __init__ (self, number, contents):
676         self.pitches = []
677         self.frame = None
678         self.finale = contents[:7]
679
680         self.notelist = ziplist (contents[7:])
681         self.duration  = None
682         self.next = None
683         self.prev = None
684         self.number = number
685         self.note_prefix= ''
686         self.note_suffix = ''
687         self.chord_suffix = ''
688         self.chord_prefix = ''
689         self.tuplet = None
690         self.grace = 0
691         
692     def measure (self):
693         if not self.frame:
694             return None
695         return self.frame.measure
696
697     def length (self):
698         if self.grace:
699             return (0,1)
700         
701         l = (1, self.duration[0])
702
703         d = 1 << self.duration[1]
704
705         dotfact = rat_subtract ((2,1), (1,d))
706         mylen =  rat_multiply (dotfact, l)
707
708         if self.tuplet:
709             mylen = rat_multiply (mylen, self.tuplet.factor())
710         return mylen
711         
712
713     def EDU_duration (self):
714         return self.finale[2]
715     def set_duration (self):
716         self.duration = EDU_to_duration(self.EDU_duration ())
717         
718     def calculate (self):
719         self.find_realpitch ()
720         self.set_duration ()
721
722         flag = self.finale[4]
723         if Chord.GRACE_MASK & flag:
724             self.grace = 1
725         
726     
727     def find_realpitch (self):
728
729         meas = self.measure ()
730         tiestart = 0
731         if not meas or not meas.global_measure  :
732             sys.stderr.write ('note %d not in measure\n' % self.number)
733         elif not meas.global_measure.scale:
734             sys.stderr.write ('note %d: no scale in this measure.' % self.number)
735         else:
736             
737             for p in self.notelist:
738                 (pitch, flag) = p
739
740
741                 nib1 = pitch & 0x0f
742                 
743                 if nib1 > 8:
744                     nib1 = -(nib1 - 8)
745                 rest = pitch / 16
746
747                 scale =  meas.global_measure.scale 
748                 (sn, sa) =scale[rest % 7]
749                 sn = sn + (rest - (rest%7)) + 7
750                 acc = sa + nib1
751                 self.pitches.append ((sn, acc))
752                 tiestart =  tiestart or (flag & Chord.TIE_START_MASK)
753         if tiestart :
754             self.chord_suffix = self.chord_suffix + ' ~ '
755         
756     REST_MASK = 0x40000000L
757     TIE_START_MASK = 0x40000000L
758     GRACE_MASK = 0x00800000L
759     
760     def ly_string (self):
761         s = ''
762
763         rest = ''
764
765
766         if not (self.finale[4] & Chord.REST_MASK):
767             rest = 'r'
768         
769         for p in self.pitches:
770             (n,a) =  p
771             o = n/ 7
772             n = n % 7
773
774             nn = lily_notename ((n,a))
775
776             if o < 0:
777                 nn = nn + (',' * -o)
778             elif o > 0:
779                 nn = nn + ('\'' * o)
780                 
781             if s:
782                 s = s + ' '
783
784             if rest:
785                 nn = rest
786                 
787             s = s + nn 
788
789         if not self.pitches:
790             s  = 'r'
791         if len (self.pitches) > 1:
792             s = '<%s>' % s
793
794         s = s + '%d%s' % (self.duration[0], '.'* self.duration[1])
795         s = self.note_prefix + s + self.note_suffix
796         
797         s = self.chord_prefix + s + self.chord_suffix
798
799         return s
800
801
802 def fill_list_to (list, no):
803     """
804 Add None to LIST until it contains entry number NO.
805     """
806     while len (list) <= no:
807         list.extend ([None] * (no - len(list) + 1))
808     return list
809
810 def read_finale_value (str):
811     """
812 Pry off one value from STR. The value may be $hex, decimal, or "string".
813 Return: (value, rest-of-STR)
814     """
815     while str and str[0] in ' \t\n':
816         str = str[1:]
817
818     if not str:
819         return (None,str)
820     
821     if str[0] == '$':
822         str = str [1:]
823
824         hex = ''
825         while str and str[0] in '0123456789ABCDEF':
826             hex = hex  + str[0]
827             str = str[1:]
828
829         
830         return (string.atol (hex, 16), str)
831     elif str[0] == '"':
832         str = str[1:]
833         s = ''
834         while str and str[0] <> '"':
835             s = s + str[0]
836             str = str[1:]
837
838         return (s,str)
839     elif str[0] in '-0123456789':
840         dec = ''
841         while str and str[0] in '-0123456789':
842             dec = dec  + str[0]
843             str = str[1:]
844             
845         return (string.atoi (dec), str)
846     else:
847         sys.stderr.write ("cannot convert `%s'\n" % str)
848         return (None, str)
849
850
851
852     
853 def parse_etf_file (fn, tag_dict):
854
855     """ Read FN, putting ETF info into
856     a giant dictionary.  The keys of TAG_DICT indicate which tags
857     to put into the dict.
858     """
859     
860     sys.stderr.write ('parsing ... ' )
861     f = open (fn)
862     
863     gulp = re.sub ('[\n\r]+', '\n',  f.read ())
864     ls = string.split (gulp, '\n^')
865
866     etf_file_dict = {}
867     for k in tag_dict.keys (): 
868         etf_file_dict[k] = {}
869
870     last_tag = None
871     last_numbers = None
872
873
874     for l in  ls:
875         m = re.match ('^([a-zA-Z0-9&]+)\(([^)]+)\)', l)
876         if m and tag_dict.has_key (m.group (1)):
877             tag = m.group (1)
878
879             indices = tuple (map (string.atoi, string.split (m.group (2), ',')))
880             content = l[m.end (2)+1:]
881
882
883             tdict = etf_file_dict[tag]
884             if not tdict.has_key (indices):
885                 tdict[indices] = []
886
887
888             parsed = []
889
890             if tag == 'verse' or tag == 'block':
891                 m2 = re.match ('(.*)\^end', content)
892                 if m2:
893                     parsed = [m2.group (1)]
894             else:
895                 while content:
896                     (v, content) = read_finale_value (content)
897                     if v <> None:
898                         parsed.append (v)
899
900             tdict [indices].extend (parsed)
901
902             last_indices = indices
903             last_tag = tag
904
905             continue
906
907 # let's not do this: this really confuses when eE happens to be before  a ^text.
908 #                if last_tag and last_indices:
909 #                        etf_file_dict[last_tag][last_indices].append (l)
910             
911     sys.stderr.write ('\n') 
912     return etf_file_dict
913
914     
915
916
917
918 class Etf_file:
919     def __init__ (self, name):
920         self.measures = [None]
921         self.chords = [None]
922         self.frames = [None]
923         self.tuplets = [None]
924         self.staffs = [None]
925         self.slurs = [None]
926         self.articulations = [None]
927         self.syllables = [None]
928         self.verses = [None]
929         self.articulation_defs = [None]
930
931         ## do it
932         self.parse (name)
933
934     def get_global_measure (self, no):
935         fill_list_to (self.measures, no)
936         if self.measures[no] == None:
937             self.measures [no] = Global_measure (no)
938
939         return self.measures[no]
940
941         
942     def get_staff(self,staffno):
943         fill_list_to (self.staffs, staffno)
944         if self.staffs[staffno] == None:
945             self.staffs[staffno] = Staff (staffno)
946
947         return self.staffs[staffno]
948
949     # staff-spec
950     def try_IS (self, indices, contents):
951         pass
952
953     def try_BC (self, indices, contents):
954         bn = indices[0]
955         where = contents[0] / 1024.0
956     def try_TP(self,  indices, contents):
957         (nil, num) = indices
958
959         if self.tuplets[-1] == None or num <> self.tuplets[-1].start_note:
960             self.tuplets.append (Tuplet (num))
961
962         self.tuplets[-1].append_finale (contents)
963
964     def try_IM (self, indices, contents):
965         (a,b) = indices
966         fin = contents
967         self.articulations.append (Articulation (a,b,fin))
968     def try_verse (self, indices, contents):
969         a = indices[0]
970         body = contents[0]
971
972         body = re.sub (r"""\^[a-z]+\([^)]+\)""", "", body)
973         body = re.sub ("\^[a-z]+", "", body)
974         self.verses.append (Verse (a, body))
975     def try_ve (self,indices, contents):
976         (a,b) = indices
977         self.syllables.append (Syllable (a,b,contents))
978
979     def try_eE (self,indices, contents):
980         no = indices[0]
981         (prev, next, dur, pos, entryflag, extended, follow) = contents[:7]
982
983         fill_list_to (self.chords, no)
984         self.chords[no]  =Chord (no, contents)
985
986     def try_Sx(self,indices, contents):
987         slurno = indices[0]
988         fill_list_to (self.slurs, slurno)
989         self.slurs[slurno] = Slur(slurno, contents)
990
991     def try_IX (self, indices, contents):
992         n = indices[0]
993         a = contents[0]
994         b = contents[1]
995
996         ix= None
997         try:
998             ix = self.articulation_defs[n]
999         except IndexError:
1000             ix = Articulation_def (n,a,b)
1001             self.articulation_defs.append (Articulation_def (n, a, b))
1002
1003     def try_GF(self, indices, contents):
1004         (staffno,measno) = indices
1005
1006         st = self.get_staff (staffno)
1007         meas = st.get_measure (measno)
1008         meas.finale = contents
1009         
1010     def try_FR(self, indices, contents):
1011         frameno = indices [0]
1012         
1013         startnote = contents[0]
1014         endnote = contents[1]
1015
1016         fill_list_to (self.frames, frameno)
1017     
1018         self.frames[frameno] = Frame ((frameno, startnote, endnote))
1019     
1020     def try_MS (self, indices, contents):
1021         measno = indices[0]
1022         keynum = contents[1]
1023         meas =self. get_global_measure (measno)
1024
1025         meas.set_key_sig (keynum)
1026
1027         beats = contents[2]
1028         beatlen = contents[3]
1029         meas.set_timesig ((beats, beatlen))
1030
1031         meas_flag1 = contents[4]
1032         meas_flag2 = contents[5]
1033
1034         meas.set_flags (meas_flag1, meas_flag2);
1035
1036
1037     routine_dict = {
1038         'MS': try_MS,
1039         'FR': try_FR,
1040         'GF': try_GF,
1041         'IX': try_IX,
1042         'Sx' : try_Sx,
1043         'eE' : try_eE,
1044         'verse' : try_verse,
1045         've' : try_ve,
1046         'IM' : try_IM,
1047         'TP' : try_TP,
1048         'BC' : try_BC,
1049         'IS' : try_IS,
1050         }
1051     
1052     def parse (self, etf_dict):
1053         sys.stderr.write ('reconstructing ...')
1054         sys.stderr.flush ()
1055
1056         for (tag,routine) in Etf_file.routine_dict.items ():
1057             ks = etf_dict[tag].keys ()
1058             ks.sort ()
1059             for k in ks:
1060                 routine (self, k, etf_dict[tag][k])
1061             
1062         sys.stderr.write ('processing ...')
1063         sys.stderr.flush ()
1064
1065         self.unthread_entries ()
1066
1067         for st in self.staffs[1:]:
1068             if not st:
1069                 continue
1070             mno = 1
1071             for m in st.measures[1:]:
1072                 if not m:
1073                     continue
1074                 
1075                 m.calculate()
1076                 try:
1077                     m.global_measure = self.measures[mno]
1078                 except IndexError:
1079                     sys.stderr.write ("Non-existent global measure %d" % mno)
1080                     continue
1081                 
1082                 frame_obj_list = [None]
1083                 for frno in m.frames:
1084                     try:
1085                         fr = self.frames[frno]
1086                         frame_obj_list.append (fr)
1087                     except IndexError:
1088                         sys.stderr.write ("\nNon-existent frame %d"  % frno)
1089
1090                 m.frames = frame_obj_list
1091                 for fr in frame_obj_list[1:]:
1092                     if not fr:
1093                         continue
1094                     
1095                     fr.set_measure (m)
1096                     
1097                     fr.chords = self.get_thread (fr.start, fr.end)
1098                     for c in fr.chords:
1099                         c.frame = fr
1100                 mno = mno + 1
1101
1102         for c in self.chords[1:]:
1103             if c:
1104                 c.calculate()
1105
1106         for f in self.frames[1:]:
1107             if f:
1108                 f.calculate ()
1109             
1110         for t in self.tuplets[1:]:
1111             t.calculate (self.chords)
1112             
1113         for s in self.slurs[1:]:
1114             if s:
1115                 s.calculate (self.chords)
1116             
1117         for s in self.articulations[1:]:
1118             s.calculate (self.chords, self.articulation_defs)
1119             
1120     def get_thread (self, startno, endno):
1121
1122         thread = []
1123
1124         c = None
1125         try:
1126             c = self.chords[startno]
1127         except IndexError:
1128             sys.stderr.write ("Huh? Frame has invalid bounds (%d,%d)\n" % (startno, endno))
1129             return []
1130
1131         
1132         while c and c.number <> endno:
1133             thread.append (c)
1134             c = c.next
1135
1136         if c: 
1137             thread.append (c)
1138         
1139         return thread
1140
1141     def dump (self):
1142         str = ''
1143         staffs = []
1144         for s in self.staffs[1:]:
1145             if s:
1146                 str = str + '\n\n' + s.dump () 
1147                 staffs.append ('\\' + s.staffid ())
1148
1149
1150         # should use \addlyrics ?
1151
1152         for v in self.verses[1:]:
1153             str = str + v.dump()
1154
1155         if len (self.verses) > 1:
1156             sys.stderr.write ("\nLyrics found; edit to use \\addlyrics to couple to a staff\n")
1157             
1158         if staffs:
1159             str += '\\version "2.3.25"\n'
1160             str = str + '<<\n  %s\n>> } ' % string.join (staffs)
1161             
1162         return str
1163
1164
1165     def __str__ (self):
1166         return 'ETF FILE %s %s' % (self.measures,  self.entries)
1167     
1168     def unthread_entries (self):
1169         for e in self.chords[1:]:
1170             if not e:
1171                 continue
1172
1173             e.prev = self.chords[e.finale[0]]
1174             e.next = self.chords[e.finale[1]]
1175
1176 def identify():
1177     sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1178
1179 def warranty ():
1180     identify ()
1181     sys.stdout.write ('''
1182 Copyright (c) %s by
1183
1184  Han-Wen Nienhuys
1185  Jan Nieuwenhuizen
1186
1187 %s
1188 %s
1189 ''' % ( '2001--2006',
1190    _('Distributed under terms of the GNU General Public License.'),
1191    _('It comes with NO WARRANTY.')))
1192
1193
1194
1195 def get_option_parser ():
1196     p = ly.get_option_parser (usage=_ ("%s [OPTION]... ETF-FILE") % 'etf2ly',
1197                  version="etf2ly (LilyPond) @TOPLEVEL_VERSION@",
1198                  description=_ ("""Enigma Transport Format is a format used by Coda Music Technology's
1199 Finale product.  etf2ly converts a subset of ETF to a ready-to-use LilyPond file."""))
1200     p.add_option ('-o', '--output', help=_ ("write output to FILE"),
1201            metavar=_("FILE"),
1202            action='store')
1203     p.add_option ('-w', '--warranty', help=_ ("show warranty and copyright"),
1204            action='store_true',
1205            ),
1206
1207     p.add_option_group ('bugs',
1208                         description=(_ ('Report bugs via')
1209                                      + ''' http://post.gmane.org/post.php'''
1210                                      '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
1211     return p
1212
1213 def do_options ():
1214     opt_parser = get_option_parser()
1215     (options,args) = opt_parser.parse_args ()
1216     if options.warranty:
1217         warranty ()
1218         sys.exit (0)
1219
1220     return (options,args)
1221
1222 (options, files) = do_options()
1223 identify()
1224
1225 out_filename = options.output
1226
1227 e = None
1228 for f in files:
1229     if f == '-':
1230         f = ''
1231
1232     sys.stderr.write ('Processing `%s\'\n' % f)
1233
1234     dict = parse_etf_file (f, Etf_file.routine_dict)
1235     e = Etf_file(dict)
1236     if not out_filename:
1237         out_filename = os.path.basename (re.sub ('(?i).etf$', '.ly', f))
1238         
1239     if out_filename == f:
1240         out_filename = os.path.basename (f + '.ly')
1241         
1242     sys.stderr.write ('Writing `%s\'' % out_filename)
1243     ly = e.dump()
1244
1245     
1246     
1247     fo = open (out_filename, 'w')
1248     fo.write ('%% lily was here -- automatically converted by etf2ly from %s\n' % f)
1249     fo.write(ly)
1250     fo.close ()
1251