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