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