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