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