]> git.donarmstrong.com Git - lilypond.git/blob - scripts/etf2ly.py
* The grand 2005-2006 replace.
[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 rational_to_lily_skip (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                 in_grace = 0
467                 for c in self.chords:
468                         if c.grace and (lastch == None or (not lastch.grace)):
469                                 c.chord_prefix = r'\grace {' + c.chord_prefix
470                                 in_grace = 1
471                         elif not c.grace and lastch and lastch.grace:
472                                 lastch.chord_suffix = lastch.chord_suffix + ' } '
473                                 in_grace = 0
474                                 
475                         lastch = c
476
477                 if lastch and in_grace:
478                         lastch.chord_suffix += '}' 
479
480                 
481         def dump (self):
482                 str = '%% FR(%d)\n' % self.number
483                 left = self.measure.global_measure.length ()
484
485                 
486                 ln = ''
487                 for c in self.chords:
488                         add = c.ly_string () + ' '
489                         if len (ln) + len(add) > 72:
490                                 str = str + ln + '\n'
491                                 ln = ''
492                         ln = ln + add
493                         left = rat_subtract (left, c.length ())
494
495                 str = str + ln 
496                 
497                 if left[0] < 0:
498                         sys.stderr.write ("""\nHuh? Going backwards in frame no %d, start/end (%d,%d)""" % (self.number, self.start, self.end))
499                         left = (0,1)
500                 if left[0]:
501                         str = str + rational_to_lily_skip (left)
502
503                 str = str + '  | \n'
504                 return str
505                 
506 def encodeint (i):
507         return chr ( i  + ord ('A'))
508
509 class Staff:
510         def __init__ (self, number):
511                 self.number = number
512                 self.measures = []
513
514         def get_measure (self, no):
515                 fill_list_to (self.measures, no)
516
517                 if self.measures[no] == None:
518                         m = Measure (no)
519                         self.measures [no] =m
520                         m.staff = self
521
522                 return self.measures[no]
523         def staffid (self):
524                 return 'staff' + encodeint (self.number - 1)
525         def layerid (self, l):
526                 return self.staffid() +  'layer%s' % chr (l -1 + ord ('A'))
527         
528         def dump_time_key_sigs (self):
529                 k  = ''
530                 last_key = None
531                 last_time = None
532                 last_clef = None
533                 gap = (0,1)
534                 for m in self.measures[1:]:
535                         if not m or not m.valid:
536                                 continue # ugh.
537                         
538                         g = m.global_measure
539                         e = ''
540                         
541                         if g:
542                                 if g.key_signature and not g.key_signature.equal(last_key):
543                                         pitch= g.key_signature.pitch
544                                         e = e + "\\key %s %s " % (lily_notename (pitch),
545                                                                   g.key_signature.signature_type())
546                                         
547                                         last_key = g.key_signature
548                                 if last_time <> g.timesig :
549                                         e = e + "\\time %d/%d " % g.timesig
550                                         last_time = g.timesig
551
552                                 if 'start' in g.repeats:
553                                         e = e + ' \\bar "|:" ' 
554
555
556                                 # we don't attempt voltas since they fail easily.
557                                 if 0 : # and g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket:
558                                         strs = []
559                                         if g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket == 'end':
560                                                 strs.append ('#f')
561
562                                         
563                                         if g.bracket == 'start':
564                                                 strs.append ('"0."')
565
566                                         str = string.join (map (lambda x: '(volta %s)' % x, strs))
567                                         
568                                         e = e + ' \\set Score.repeatCommands =  #\'(%s) ' % str
569
570                                 if g.force_break:
571                                         e = e + ' \\break '  
572                         
573                         if last_clef <> m.clef :
574                                 e = e + '\\clef "%s"' % lily_clef (m.clef)
575                                 last_clef = m.clef
576                         if e:
577                                 if gap <> (0,1):
578                                         k = k +' ' + rational_to_lily_skip (gap) + '\n'
579                                 gap = (0,1)
580                                 k = k + e
581                                 
582                         if g:
583                                 gap = rat_add (gap, g.length ())
584                                 if 'stop' in g.repeats:
585                                         k = k + ' \\bar ":|" '
586                                 
587                 k = '%sglobal = { %s }\n\n ' % (self.staffid (), k)
588                 return k
589         
590         def dump (self):
591                 str = ''
592
593
594                 layerids = []
595                 for x in range (1,5): # 4 layers.
596                         laystr =  ''
597                         last_frame = None
598                         first_frame = None
599                         gap = (0,1)
600                         for m in self.measures[1:]:
601                                 if not m or not m.valid:
602                                         sys.stderr.write ("Skipping non-existant or invalid measure\n")
603                                         continue
604
605                                 fr = None
606                                 try:
607                                         fr = m.frames[x]
608                                 except IndexError:
609                                         sys.stderr.write ("Skipping nonexistent frame %d\n" % x)
610                                         laystr = laystr + "%% non existent frame %d (skipped) \n" % x
611                                 if fr:
612                                         first_frame = fr
613                                         if gap <> (0,1):
614                                                 laystr = laystr +'} %s {\n ' % rational_to_lily_skip (gap)
615                                                 gap = (0,1)
616                                         laystr = laystr + fr.dump ()
617                                 else:
618                                         if m.global_measure :
619                                                 gap = rat_add (gap, m.global_measure.length ())
620                                         else:
621                                                 sys.stderr.write ( \
622                                                         "No global measure for staff %d measure %d\n"
623                                                         % (self.number, m.number))
624                         if first_frame:
625                                 l = self.layerid (x)
626                                 laystr = '%s = { {  %s } }\n\n' % (l, laystr)
627                                 str = str  + laystr
628                                 layerids.append (l)
629
630                 str = str +  self.dump_time_key_sigs ()         
631                 stafdef = '\\%sglobal' % self.staffid ()
632                 for i in layerids:
633                         stafdef = stafdef + ' \\' + i
634                         
635
636                 str = str + '%s = \\context Staff = %s <<\n %s\n >>\n' % \
637                       (self.staffid (), self.staffid (), stafdef)
638                 return str
639
640                                 
641
642 def ziplist (l):
643         if len (l) < 2:
644                 return []
645         else:
646                 return [(l[0], l[1])] + ziplist (l[2:])
647
648
649 class Chord:
650         def __init__ (self, number, contents):
651                 self.pitches = []
652                 self.frame = None
653                 self.finale = contents[:7]
654
655                 self.notelist = ziplist (contents[7:])
656                 self.duration  = None
657                 self.next = None
658                 self.prev = None
659                 self.number = number
660                 self.note_prefix= ''
661                 self.note_suffix = ''
662                 self.chord_suffix = ''
663                 self.chord_prefix = ''
664                 self.tuplet = None
665                 self.grace = 0
666                 
667         def measure (self):
668                 if not self.frame:
669                         return None
670                 return self.frame.measure
671
672         def length (self):
673                 if self.grace:
674                         return (0,1)
675                 
676                 l = (1, self.duration[0])
677
678                 d = 1 << self.duration[1]
679
680                 dotfact = rat_subtract ((2,1), (1,d))
681                 mylen =  rat_multiply (dotfact, l)
682
683                 if self.tuplet:
684                         mylen = rat_multiply (mylen, self.tuplet.factor())
685                 return mylen
686                 
687
688         def EDU_duration (self):
689                 return self.finale[2]
690         def set_duration (self):
691                 self.duration = EDU_to_duration(self.EDU_duration ())
692                 
693         def calculate (self):
694                 self.find_realpitch ()
695                 self.set_duration ()
696
697                 flag = self.finale[4]
698                 if Chord.GRACE_MASK & flag:
699                         self.grace = 1
700                 
701         
702         def find_realpitch (self):
703
704                 meas = self.measure ()
705                 tiestart = 0
706                 if not meas or not meas.global_measure  :
707                         sys.stderr.write ('note %d not in measure\n' % self.number)
708                 elif not meas.global_measure.scale:
709                         sys.stderr.write ('note %d: no scale in this measure.' % self.number)
710                 else:
711                         
712                         for p in self.notelist:
713                                 (pitch, flag) = p
714
715
716                                 nib1 = pitch & 0x0f
717                                 
718                                 if nib1 > 8:
719                                         nib1 = -(nib1 - 8)
720                                 rest = pitch / 16
721
722                                 scale =  meas.global_measure.scale 
723                                 (sn, sa) =scale[rest % 7]
724                                 sn = sn + (rest - (rest%7)) + 7
725                                 acc = sa + nib1
726                                 self.pitches.append ((sn, acc))
727                                 tiestart =  tiestart or (flag & Chord.TIE_START_MASK)
728                 if tiestart :
729                         self.chord_suffix = self.chord_suffix + ' ~ '
730                 
731         REST_MASK = 0x40000000L
732         TIE_START_MASK = 0x40000000L
733         GRACE_MASK = 0x00800000L
734         
735         def ly_string (self):
736                 s = ''
737
738                 rest = ''
739
740
741                 if not (self.finale[4] & Chord.REST_MASK):
742                         rest = 'r'
743                 
744                 for p in self.pitches:
745                         (n,a) =  p
746                         o = n/ 7
747                         n = n % 7
748
749                         nn = lily_notename ((n,a))
750
751                         if o < 0:
752                                 nn = nn + (',' * -o)
753                         elif o > 0:
754                                 nn = nn + ('\'' * o)
755                                 
756                         if s:
757                                 s = s + ' '
758
759                         if rest:
760                                 nn = rest
761                                 
762                         s = s + nn 
763
764                 if not self.pitches:
765                         s  = 'r'
766                 if len (self.pitches) > 1:
767                         s = '<%s>' % s
768
769                 s = s + '%d%s' % (self.duration[0], '.'* self.duration[1])
770                 s = self.note_prefix + s + self.note_suffix
771                 
772                 s = self.chord_prefix + s + self.chord_suffix
773
774                 return s
775
776
777 def fill_list_to (list, no):
778         """
779 Add None to LIST until it contains entry number NO.
780         """
781         while len (list) <= no:
782                 list.extend ([None] * (no - len(list) + 1))
783         return list
784
785 def read_finale_value (str):
786         """
787 Pry off one value from STR. The value may be $hex, decimal, or "string".
788 Return: (value, rest-of-STR)
789         """
790         while str and str[0] in ' \t\n':
791                 str = str[1:]
792
793         if not str:
794                 return (None,str)
795         
796         if str[0] == '$':
797                 str = str [1:]
798
799                 hex = ''
800                 while str and str[0] in '0123456789ABCDEF':
801                         hex = hex  + str[0]
802                         str = str[1:]
803
804                 
805                 return (string.atol (hex, 16), str)
806         elif str[0] == '"':
807                 str = str[1:]
808                 s = ''
809                 while str and str[0] <> '"':
810                         s = s + str[0]
811                         str = str[1:]
812
813                 return (s,str)
814         elif str[0] in '-0123456789':
815                 dec = ''
816                 while str and str[0] in '-0123456789':
817                         dec = dec  + str[0]
818                         str = str[1:]
819                         
820                 return (string.atoi (dec), str)
821         else:
822                 sys.stderr.write ("can't convert `%s'\n" % str)
823                 return (None, str)
824
825
826
827         
828 def parse_etf_file (fn, tag_dict):
829
830         """ Read FN, putting ETF info into
831         a giant dictionary.  The keys of TAG_DICT indicate which tags
832         to put into the dict.
833         """
834         
835         sys.stderr.write ('parsing ... ' )
836         f = open (fn)
837         
838         gulp = re.sub ('[\n\r]+', '\n',  f.read ())
839         ls = string.split (gulp, '\n^')
840
841         etf_file_dict = {}
842         for k in tag_dict.keys (): 
843                 etf_file_dict[k] = {}
844
845         last_tag = None
846         last_numbers = None
847
848
849         for l in  ls:
850                 m = re.match ('^([a-zA-Z0-9&]+)\(([^)]+)\)', l)
851                 if m and tag_dict.has_key (m.group (1)):
852                         tag = m.group (1)
853
854                         indices = tuple (map (string.atoi, string.split (m.group (2), ',')))
855                         content = l[m.end (2)+1:]
856
857
858                         tdict = etf_file_dict[tag]
859                         if not tdict.has_key (indices):
860                                 tdict[indices] = []
861
862
863                         parsed = []
864
865                         if tag == 'verse' or tag == 'block':
866                                 m2 = re.match ('(.*)\^end', content)
867                                 if m2:
868                                         parsed = [m2.group (1)]
869                         else:
870                                 while content:
871                                         (v, content) = read_finale_value (content)
872                                         if v <> None:
873                                                 parsed.append (v)
874
875                         tdict [indices].extend (parsed)
876
877                         last_indices = indices
878                         last_tag = tag
879
880                         continue
881
882 # let's not do this: this really confuses when eE happens to be before  a ^text.
883 #               if last_tag and last_indices:
884 #                       etf_file_dict[last_tag][last_indices].append (l)
885                         
886         sys.stderr.write ('\n') 
887         return etf_file_dict
888
889         
890
891
892
893 class Etf_file:
894         def __init__ (self, name):
895                 self.measures = [None]
896                 self.chords = [None]
897                 self.frames = [None]
898                 self.tuplets = [None]
899                 self.staffs = [None]
900                 self.slurs = [None]
901                 self.articulations = [None]
902                 self.syllables = [None]
903                 self.verses = [None]
904                 self.articulation_defs = [None]
905
906                 ## do it
907                 self.parse (name)
908
909         def get_global_measure (self, no):
910                 fill_list_to (self.measures, no)
911                 if self.measures[no] == None:
912                         self.measures [no] = Global_measure (no)
913
914                 return self.measures[no]
915
916                 
917         def get_staff(self,staffno):
918                 fill_list_to (self.staffs, staffno)
919                 if self.staffs[staffno] == None:
920                         self.staffs[staffno] = Staff (staffno)
921
922                 return self.staffs[staffno]
923
924         # staff-spec
925         def try_IS (self, indices, contents):
926                 pass
927
928         def try_BC (self, indices, contents):
929                 bn = indices[0]
930                 where = contents[0] / 1024.0
931         def try_TP(self,  indices, contents):
932                 (nil, num) = indices
933
934                 if self.tuplets[-1] == None or num <> self.tuplets[-1].start_note:
935                         self.tuplets.append (Tuplet (num))
936
937                 self.tuplets[-1].append_finale (contents)
938
939         def try_IM (self, indices, contents):
940                 (a,b) = indices
941                 fin = contents
942                 self.articulations.append (Articulation (a,b,fin))
943         def try_verse (self, indices, contents):
944                 a = indices[0]
945                 body = contents[0]
946
947                 body = re.sub (r"""\^[a-z]+\([^)]+\)""", "", body)
948                 body = re.sub ("\^[a-z]+", "", body)
949                 self.verses.append (Verse (a, body))
950         def try_ve (self,indices, contents):
951                 (a,b) = indices
952                 self.syllables.append (Syllable (a,b,contents))
953
954         def try_eE (self,indices, contents):
955                 no = indices[0]
956                 (prev, next, dur, pos, entryflag, extended, follow) = contents[:7]
957
958                 fill_list_to (self.chords, no)
959                 self.chords[no]  =Chord (no, contents)
960
961         def try_Sx(self,indices, contents):
962                 slurno = indices[0]
963                 fill_list_to (self.slurs, slurno)
964                 self.slurs[slurno] = Slur(slurno, contents)
965
966         def try_IX (self, indices, contents):
967                 n = indices[0]
968                 a = contents[0]
969                 b = contents[1]
970
971                 ix= None
972                 try:
973                         ix = self.articulation_defs[n]
974                 except IndexError:
975                         ix = Articulation_def (n,a,b)
976                         self.articulation_defs.append (Articulation_def (n, a, b))
977
978         def try_GF(self, indices, contents):
979                 (staffno,measno) = indices
980
981                 st = self.get_staff (staffno)
982                 meas = st.get_measure (measno)
983                 meas.finale = contents
984                 
985         def try_FR(self, indices, contents):
986                 frameno = indices [0]
987                 
988                 startnote = contents[0]
989                 endnote = contents[1]
990
991                 fill_list_to (self.frames, frameno)
992         
993                 self.frames[frameno] = Frame ((frameno, startnote, endnote))
994         
995         def try_MS (self, indices, contents):
996                 measno = indices[0]
997                 keynum = contents[1]
998                 meas =self. get_global_measure (measno)
999
1000                 meas.set_key_sig (keynum)
1001
1002                 beats = contents[2]
1003                 beatlen = contents[3]
1004                 meas.set_timesig ((beats, beatlen))
1005
1006                 meas_flag1 = contents[4]
1007                 meas_flag2 = contents[5]
1008
1009                 meas.set_flags (meas_flag1, meas_flag2);
1010
1011
1012         routine_dict = {
1013                 'MS': try_MS,
1014                 'FR': try_FR,
1015                 'GF': try_GF,
1016                 'IX': try_IX,
1017                 'Sx' : try_Sx,
1018                 'eE' : try_eE,
1019                 'verse' : try_verse,
1020                 've' : try_ve,
1021                 'IM' : try_IM,
1022                 'TP' : try_TP,
1023                 'BC' : try_BC,
1024                 'IS' : try_IS,
1025                 }
1026         
1027         def parse (self, etf_dict):
1028                 sys.stderr.write ('reconstructing ...')
1029                 sys.stderr.flush ()
1030
1031                 for (tag,routine) in Etf_file.routine_dict.items ():
1032                         ks = etf_dict[tag].keys ()
1033                         ks.sort ()
1034                         for k in ks:
1035                                 routine (self, k, etf_dict[tag][k])
1036                         
1037                 sys.stderr.write ('processing ...')
1038                 sys.stderr.flush ()
1039
1040                 self.unthread_entries ()
1041
1042                 for st in self.staffs[1:]:
1043                         if not st:
1044                                 continue
1045                         mno = 1
1046                         for m in st.measures[1:]:
1047                                 if not m:
1048                                         continue
1049                                 
1050                                 m.calculate()
1051                                 try:
1052                                         m.global_measure = self.measures[mno]
1053                                 except IndexError:
1054                                         sys.stderr.write ("Non-existent global measure %d" % mno)
1055                                         continue
1056                                 
1057                                 frame_obj_list = [None]
1058                                 for frno in m.frames:
1059                                         try:
1060                                                 fr = self.frames[frno]
1061                                                 frame_obj_list.append (fr)
1062                                         except IndexError:
1063                                                 sys.stderr.write ("\nNon-existent frame %d"  % frno)
1064
1065                                 m.frames = frame_obj_list
1066                                 for fr in frame_obj_list[1:]:
1067                                         if not fr:
1068                                                 continue
1069                                         
1070                                         fr.set_measure (m)
1071                                         
1072                                         fr.chords = self.get_thread (fr.start, fr.end)
1073                                         for c in fr.chords:
1074                                                 c.frame = fr
1075                                 mno = mno + 1
1076
1077                 for c in self.chords[1:]:
1078                         if c:
1079                                 c.calculate()
1080
1081                 for f in self.frames[1:]:
1082                         if f:
1083                                 f.calculate ()
1084                         
1085                 for t in self.tuplets[1:]:
1086                         t.calculate (self.chords)
1087                         
1088                 for s in self.slurs[1:]:
1089                         if s:
1090                                 s.calculate (self.chords)
1091                         
1092                 for s in self.articulations[1:]:
1093                         s.calculate (self.chords, self.articulation_defs)
1094                         
1095         def get_thread (self, startno, endno):
1096
1097                 thread = []
1098
1099                 c = None
1100                 try:
1101                         c = self.chords[startno]
1102                 except IndexError:
1103                         sys.stderr.write ("Huh? Frame has invalid bounds (%d,%d)\n" % (startno, endno))
1104                         return []
1105
1106                 
1107                 while c and c.number <> endno:
1108                         thread.append (c)
1109                         c = c.next
1110
1111                 if c: 
1112                         thread.append (c)
1113                 
1114                 return thread
1115
1116         def dump (self):
1117                 str = ''
1118                 staffs = []
1119                 for s in self.staffs[1:]:
1120                         if s:
1121                                 str = str + '\n\n' + s.dump () 
1122                                 staffs.append ('\\' + s.staffid ())
1123
1124
1125                 # should use \addlyrics ?
1126
1127                 for v in self.verses[1:]:
1128                         str = str + v.dump()
1129
1130                 if len (self.verses) > 1:
1131                         sys.stderr.write ("\nLyrics found; edit to use \\addlyrics to couple to a staff\n")
1132                         
1133                 if staffs:
1134                         str += '\\version "2.3.25"\n'
1135                         str = str + '<<\n  %s\n>> } ' % string.join (staffs)
1136                         
1137                 return str
1138
1139
1140         def __str__ (self):
1141                 return 'ETF FILE %s %s' % (self.measures,  self.entries)
1142         
1143         def unthread_entries (self):
1144                 for e in self.chords[1:]:
1145                         if not e:
1146                                 continue
1147
1148                         e.prev = self.chords[e.finale[0]]
1149                         e.next = self.chords[e.finale[1]]
1150
1151 def identify():
1152         sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1153
1154 def help ():
1155         sys.stdout.write("""Usage: etf2ly [OPTIONS]... ETF-FILE
1156
1157 Convert ETF to LilyPond.
1158
1159 Options:
1160   -h, --help          print this help
1161   -o, --output=FILE   set output filename to FILE
1162   -v, --version       show version information
1163
1164 Enigma Transport Format is a format used by Coda Music Technology's
1165 Finale product. This program will convert a subset of ETF to a
1166 ready-to-use lilypond file.
1167
1168 Report bugs via
1169
1170   http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs
1171
1172 Written by  Han-Wen Nienhuys <hanwen@cs.uu.nl>.
1173
1174 """)
1175
1176 def print_version ():
1177         sys.stdout.write (r"""etf2ly (GNU lilypond) %s
1178
1179 This is free software.  It is covered by the GNU General Public License,
1180 and you are welcome to change it and/or distribute copies of it under
1181 certain conditions.  Invoke as `midi2ly --warranty' for more information.
1182
1183 Copyright (c) 2000--2006 by Han-Wen Nienhuys <hanwen@cs.uu.nl>
1184 """ % version)
1185
1186
1187
1188 (options, files) = getopt.getopt (sys.argv[1:], 'vo:h', ['help','version', 'output='])
1189 out_filename = None
1190
1191 for opt in options:
1192         o = opt[0]
1193         a = opt[1]
1194         if o== '--help' or o == '-h':
1195                 help ()
1196                 sys.exit (0)
1197         if o == '--version' or o == '-v':
1198                 print_version ()
1199                 sys.exit(0)
1200                 
1201         if o == '--output' or o == '-o':
1202                 out_filename = a
1203         else:
1204                 print o
1205                 raise getopt.error
1206
1207 identify()
1208
1209 e = None
1210 for f in files:
1211         if f == '-':
1212                 f = ''
1213
1214         sys.stderr.write ('Processing `%s\'\n' % f)
1215
1216         dict = parse_etf_file (f, Etf_file.routine_dict)
1217         e = Etf_file(dict)
1218         if not out_filename:
1219                 out_filename = os.path.basename (re.sub ('(?i).etf$', '.ly', f))
1220                 
1221         if out_filename == f:
1222                 out_filename = os.path.basename (f + '.ly')
1223                 
1224         sys.stderr.write ('Writing `%s\'' % out_filename)
1225         ly = e.dump()
1226
1227         
1228         
1229         fo = open (out_filename, 'w')
1230         fo.write ('%% lily was here -- automatically converted by etf2ly from %s\n' % f)
1231         fo.write(ly)
1232         fo.close ()
1233