]> git.donarmstrong.com Git - lilypond.git/blob - scripts/etf2ly.py
release: 1.3.93
[lilypond.git] / scripts / etf2ly.py
1 #!@PYTHON@
2
3 # info mostly taken from looking at files. See also
4 # http://www.cs.uu.nl/~hanwen/lily-devel/etf.html
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 #  * automatic `deletion' of invalid items
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         if a == -1:
178                 nn = nn + 'es'
179         elif a == -2:
180                 nn = nn + 'eses'
181         elif a == 1:
182                 nn = nn + 'is'
183         elif a == 2:
184                 nn = nn + 'isis'
185
186         return nn
187
188
189 class Tuplet:
190         def __init__ (self, number):
191                 self.start_note = number
192                 self.finale = []
193
194         def append_finale (self, fin):
195                 self.finale.append (fin)
196
197         def factor (self):
198                 n = self.finale[0][2]*self.finale[0][3]
199                 d = self.finale[0][0]*self.finale[0][1]
200                 return rat_simplify( (n, d))
201         
202         def dump_start (self):
203                 return '\\times %d/%d { ' % self.factor ()
204         
205         def dump_end (self):
206                 return ' }'
207
208         def calculate (self, chords):
209                 edu_left = self.finale[0][0] * self.finale[0][1]
210
211                 startch = chords[self.start_note]
212                 c = startch
213                 while c and edu_left:
214                         c.tuplet = self
215                         if c == startch:
216                                 c.chord_prefix = self.dump_start () + c.chord_prefix 
217
218                         if not c.grace:
219                                 edu_left = edu_left - c.EDU_duration ()
220                         if edu_left == 0:
221                                 c.chord_suffix = c.chord_suffix+ self.dump_end ()
222                         c = c.next
223
224                 if edu_left:
225                         sys.stderr.write ("\nHuh? Tuplet starting at entry %d was too short." % self.start_note)
226                 
227 class Slur:
228         def __init__ (self, number):
229                 self.number = number
230                 self.finale = []
231
232         def append_entry (self, finale_e):
233                 self.finale.append (finale_e)
234
235         def calculate (self, chords):
236                 startnote = self.finale[0][5]
237                 endnote = self.finale[3][2]
238                 try:
239                         cs = chords[startnote]
240                         ce = chords[endnote]
241
242                         if not cs or not ce:
243                                 raise IndexError
244                         
245                         cs.note_suffix = '(' + cs.note_suffix 
246                         ce.note_prefix = ce.note_prefix + ')'
247                 except IndexError:
248                         sys.stderr.write ("""\nHuh? Slur no %d between (%d,%d), with %d notes""" % (self.number,  startnote, endnote, len (chords)))
249                                          
250                 
251 class Global_measure:
252         def __init__ (self, number):
253                 self.timesig = ''
254                 self.number = number
255                 self.keysignature = None
256                 self.scale = None
257
258                 self.finale = []
259
260         def __str__ (self):
261                 return `self.finale `
262         
263         def set_timesig (self, finale):
264                 (beats, fdur) = finale
265                 (log, dots) = EDU_to_duration (fdur)
266                 assert dots == 0
267                 self.timesig = (beats, log)
268
269         def length (self):
270                 return self.timesig
271         
272         def set_keysig (self, finale):
273                 k = interpret_finale_key_sig (finale)
274                 self.keysignature = k
275                 self.scale = find_scale (k)
276
277
278 articulation_dict ={
279         11: '\\prall',
280         12: '\\mordent',
281         8: '\\fermata',
282         4: '^',
283         1: '.',
284         3: '>',
285         18: '"arp"' , # arpeggio
286 };
287
288 class Articulation:
289         def __init__ (self, a,b, finale):
290                 self.type = finale[0]
291                 self.notenumber = b
292         def calculate (self, chords):
293                 c = chords[self.notenumber]
294
295                 try:
296                         a = articulation_dict[self.type]
297                 except KeyError:
298                         sys.stderr.write ("\nUnknown articulation no. %d on note no. %d" % (self.type, self.notenumber))
299                         sys.stderr.write ("\nPlease add an entry to articulation_dict in the Python source")
300                         a = '"art"'
301                         
302                 c.note_suffix = '-' + a + c.note_suffix
303
304 class Syllable:
305         def __init__ (self, a,b , finale):
306                 self.chordnum = b
307                 self.syllable = finale[1]
308                 self.verse = finale[0]
309         def calculate (self, chords, lyrics):
310                 self.chord = chords[self.chordnum]
311
312 class Verse:
313         def __init__ (self, number, body):
314                 self.body = body
315                 self.number = number
316                 self.split_syllables ()
317         def split_syllables (self):
318                 ss = re.split ('(-| +)', self.body)
319
320                 sep = 0
321                 syls = [None]
322                 for s in ss:
323                         if sep:
324                                 septor = re.sub (" +", "", s)
325                                 septor = re.sub ("-", " -- ", septor) 
326                                 syls[-1] = syls[-1] + septor
327                         else:
328                                 syls.append (s)
329                         
330                         sep = not sep 
331
332                 self.syllables = syls
333
334         def dump (self):
335                 str = ''
336                 line = ''
337                 for s in self.syllables[1:]:
338                         line = line + ' ' + s
339                         if len (line) > 72:
340                                 str = str + ' ' * 4 + line + '\n'
341                                 line = ''
342                         
343                 str = """\nverse%s = \\lyrics {\n %s}\n""" %  (encodeint (self.number - 1) ,str)
344                 return str
345
346         
347 class Measure:
348         def __init__(self, no):
349                 self.number = no
350                 self.frames = [0] * 4
351                 self.flags = 0
352                 self.clef = 0
353                 self.finale = []
354                 self.global_measure = None
355                 self.staff = None
356                 self.valid = 1
357                 
358         def add_finale_entry (self, entry):
359                 self.finale.append (entry)
360
361         def valid (self):
362                 return self.valid
363         def calculate (self):
364                 fs = []
365
366                 if len (self.finale) < 2:
367                         fs = self.finale[0]
368                         fs = map (string.atoi, list (fs))
369                         self.clef = fs[1]
370                         self.frames = [fs[0]]
371                 else:
372                         fs = self.finale[0] + self.finale[1]
373                         
374                         fs = map (string.atoi, list (fs))
375                         self.clef = fs[0]
376                         self.flags = fs[1]
377                         self.frames = fs[2:]
378
379
380 class Frame:
381         def __init__ (self, finale):
382                 self.measure = None
383                 self.finale = finale
384                 (number, start, end ) = finale
385                 self.number = number
386                 self.start = start
387                 self.end = end
388                 self.chords  = []
389
390         def set_measure (self, m):
391                 self.measure = m
392
393         def calculate (self):
394
395                 # do grace notes.
396                 lastch = None
397                 for c in self.chords:
398                         if c.grace and (lastch == None or (not lastch.grace)):
399                                 c.chord_prefix = r'\grace {' + c.chord_prefix
400                         elif not c.grace and lastch and lastch.grace:
401                                 lastch.chord_suffix = lastch.chord_suffix + ' } '
402
403                         lastch = c
404                         
405
406                 
407         def dump (self):
408                 str = '%% FR(%d)\n' % self.number
409                 left = self.measure.global_measure.length ()
410
411                 
412                 ln = ''
413                 for c in self.chords:
414                         add = c.ly_string () + ' '
415                         if len (ln) + len(add) > 72:
416                                 str = str + ln + '\n'
417                                 ln = ''
418                         ln = ln + add
419                         left = rat_subtract (left, c.length ())
420
421                 str = str + ln 
422                 
423                 if left[0] < 0:
424                         sys.stderr.write ("""\nHuh? Going backwards in frame no %d, start/end (%d,%d)""" % (self.number, self.start, self.end))
425                         left = (0,1)
426                 if left[0]:
427                         str = str + rat_to_lily_duration (left)
428
429                 str = str + '  | \n'
430                 return str
431                 
432 def encodeint (i):
433         return chr ( i  + ord ('A'))
434
435 class Staff:
436         def __init__ (self, number):
437                 self.number = number
438                 self.measures = []
439
440         def get_measure (self, no):
441                 if len (self.measures) <= no:
442                         self.measures = self.measures + [None]* (1 + no - len (self.measures))
443
444                 if self.measures[no] == None:
445                         m = Measure (no)
446                         self.measures [no] =m
447                         m.staff = self
448
449
450                 return self.measures[no]
451         def staffid (self):
452                 return 'staff' + encodeint (self.number - 1)
453         def layerid (self, l):
454                 return self.staffid() +  'layer%s' % chr (l -1 + ord ('A'))
455         
456         def dump_time_key_sigs (self):
457                 k  = ''
458                 last_key = None
459                 last_time = None
460                 last_clef = None
461                 gap = (0,1)
462                 for m in self.measures[1:]:
463                         if not m or not m.valid:
464                                 continue # ugh.
465                         
466                         g = m.global_measure
467                         e = ''
468                         if g and last_key <> g.keysignature:
469                                 e = e + "\\key %s \\major; " % lily_notename (g.keysignature)
470                                 last_key = g.keysignature
471                         if g and last_time <> g.timesig :
472                                 e = e + "\\time %d/%d; " % g.timesig
473                                 last_time = g.timesig
474
475                         
476                         if last_clef <> m.clef :
477                                 e = e + '\\clef "%s";' % lily_clef (m.clef)
478                                 last_clef = m.clef
479                         if e:
480                                 if gap <> (0,1):
481                                         k = k +' ' + rat_to_lily_duration (gap) + '\n'
482                                 gap = (0,1)
483                                 k = k + e
484                                 
485                         if g:
486                                 gap = rat_add (gap, g.length ())
487
488                                 
489                 k = '%sglobal = \\notes  { %s }\n\n ' % (self.staffid (), k)
490                 return k
491         
492         def dump (self):
493                 str = ''
494
495
496                 layerids = []
497                 for x in range (1,5): # 4 layers.
498                         laystr =  ''
499                         last_frame = None
500                         first_frame = None
501                         gap = (0,1)
502                         for m in self.measures[1:]:
503                                 if not m or not m.valid:
504                                         continue
505
506                                 fr = None
507                                 try:
508                                         fr = m.frames[x]
509                                 except IndexError:
510                                         pass
511                                 
512                                 if fr:
513                                         first_frame = fr
514                                         if gap <> (0,1):
515                                                 laystr = laystr +'} %s {\n ' % rat_to_lily_duration (gap)
516                                                 gap = (0,1)
517                                         laystr = laystr + fr.dump ()
518                                 else:
519                                         if m.global_measure :
520                                                 gap = rat_add (gap, m.global_measure.length ())
521                                         else:
522                                                 sys.stderr.write ( \
523                                                         "No global measure for staff %d measure %d\n"
524                                                         % (self.number, m.number))
525                         if first_frame:
526                                 l = self.layerid (x)
527                                 laystr = '%s =  \\notes { { %s } }\n\n' % (l, laystr)
528                                 str = str  + laystr
529                                 layerids.append (l)
530
531                 str = str +  self.dump_time_key_sigs ()         
532                 stafdef = '\\%sglobal' % self.staffid ()
533                 for i in layerids:
534                         stafdef = stafdef + ' \\' + i
535                         
536
537                 str = str + '%s = \\context Staff = %s <\n %s\n >\n' % \
538                       (self.staffid (), self.staffid (), stafdef)
539                 return str
540
541                                 
542
543
544 class Chord:
545         def __init__ (self, finale_entry):
546                 self.pitches = []
547                 self.frame = None
548                 self.finale = finale_entry
549                 self.duration  = None
550                 self.next = None
551                 self.prev = None
552                 self.note_prefix= ''
553                 self.note_suffix = ''
554                 self.chord_suffix = ''
555                 self.chord_prefix = ''
556                 self.tuplet = None
557                 self.grace = 0
558                 
559         def measure (self):
560                 if not self.frame:
561                         return None
562                 return self.frame.measure
563
564         def length (self):
565                 if self.grace:
566                         return (0,1)
567                 
568                 l = (1, self.duration[0])
569
570                 d = 1 << self.duration[1]
571
572                 dotfact = rat_subtract ((2,1), (1,d))
573                 mylen =  rat_multiply (dotfact, l)
574
575                 if self.tuplet:
576                         mylen = rat_multiply (mylen, self.tuplet.factor())
577                 return mylen
578                 
579         def number (self):
580                 return self.finale[0][0]
581
582         def EDU_duration (self):
583                 return self.finale[0][3]
584         def set_duration (self):
585                 self.duration = EDU_to_duration(self.EDU_duration ())
586         def calculate (self):
587                 self.find_realpitch ()
588                 self.set_duration ()
589
590                 flag = self.finale[0][5]
591                 if Chord.GRACE_MASK & flag:
592                         self.grace = 1
593                 
594                 
595         def find_realpitch (self):
596                 
597                 ((no, prev, next, dur, pos, entryflag, extended, follow), notelist) = self.finale
598
599                 meas = self.measure ()
600                 tiestart = 0
601                 if not meas or not meas.global_measure  :
602                         print 'note %d not in measure' % self.number ()
603                 elif not meas.global_measure.scale:
604                         print  'note %d: no scale in this measure.' % self.number ()
605                 else:
606                         for p in notelist:
607                                 (pitch, flag) = p
608                                 
609                                 nib1 = pitch & 0x0f
610                                 if nib1 > 8:
611                                         nib1 = -(nib1 - 8)
612                                 rest = pitch / 16
613
614                                 scale =  meas.global_measure.scale 
615                                 (sn, sa) =scale[rest % 7]
616                                 sn = sn + (rest - (rest%7)) + 7
617                                 acc = sa + nib1
618                                 self.pitches.append ((sn, acc))
619                                 tiestart =  tiestart or (flag & Chord.TIE_START_MASK)
620                 if tiestart :
621                         self.chord_suffix = self.chord_suffix + ' ~ '
622                 
623         REST_MASK = 0x40000000L
624         TIE_START_MASK = 0x40000000L
625         GRACE_MASK = 0x00800000L
626         
627         def ly_string (self):
628                 s = ''
629
630                 rest = ''
631
632                 if not (self.finale[0][5] & Chord.REST_MASK):
633                         rest = 'r'
634                 
635                 for p in self.pitches:
636                         (n,a) =  p
637                         o = n/ 7
638                         n = n % 7
639
640                         nn = lily_notename ((n,a))
641
642                         if o < 0:
643                                 nn = nn + (',' * -o)
644                         elif o > 0:
645                                 nn = nn + ('\'' * o)
646                                 
647                         if s:
648                                 s = s + ' '
649
650                         if rest:
651                                 nn = rest
652                                 
653                         s = s + '%s%d%s' % (nn, self.duration[0], '.'* self.duration[1])
654
655                 if not self.pitches:
656                         s  = 'r%d%s' % (self.duration[0] , '.'* self.duration[1])
657                 s = self.note_prefix + s + self.note_suffix
658                 if len (self.pitches) > 1:
659                         s = '<%s>' % s
660                 
661                 s = self.chord_prefix + s + self.chord_suffix
662                 return s
663
664 GFre = re.compile(r"""^\^GF\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
665 BCre = re.compile (r"""^\^BC\(([0-9-]+)\) ([0-9-]+) .*$""")
666 eEre = re.compile(r"""^\^eE\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) \$([0-9A-Fa-f]+) ([0-9-]+) ([0-9-]+)""")
667 FRre = re.compile (r"""^\^FR\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
668 MSre = re.compile (r"""^\^MS\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
669 note_re = re.compile (r"""^ +([0-9-]+) \$([A-Fa-f0-9]+)""")
670 Sxre  = re.compile (r"""^\^Sx\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
671 IMre = re.compile (r"""^\^IM\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
672 vere = re.compile(r"""^\^(ve|ch|se)\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
673 versere = re.compile(r"""^\^verse\(([0-9]+)\)(.*)\^end""")
674
675 TPre = re.compile(r"""^\^TP\(([0-9]+),([0-9]+)\) *([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
676
677
678 class Etf_file:
679         def __init__ (self, name):
680                 self.measures = [None]
681                 self.entries = [None]
682                 self.chords = [None]
683                 self.frames = [None]
684                 self.tuplets = [None]
685                 self.staffs = [None]
686                 self.slur_dict = {}
687                 self.articulations = [None]
688                 self.syllables = [None]
689                 self.verses = [None]
690                 
691                 ## do it
692                 self.parse (name)
693
694         def get_global_measure (self, no):
695                 if len (self.measures) <= no:
696                         self.measures = self.measures + [None]* (1 + no - len (self.measures))
697
698                 if self.measures[no] == None:
699                         self.measures [no] = Global_measure (no)
700
701                 return self.measures[no]
702
703                 
704         def get_staff(self,staffno):
705                 if len (self.staffs) <= staffno:
706                         self.staffs = self.staffs + [None] * (1 + staffno - len (self.staffs))
707
708                 if self.staffs[staffno] == None:
709                         self.staffs[staffno] = Staff (staffno)
710
711                 return self.staffs[staffno]
712
713         # staff-spec
714         def try_IS (self, l):
715                 pass
716
717         def try_BC (self, l):
718                 m =  BCre.match  (l)
719                 if m:
720                         bn = string.atoi (m.group (1))
721                         where = string.atoi (m.group (2)) / 1024.0
722                 return m
723         def try_TP(self, l):
724                 m = TPre.match (l)
725                 if m:
726                         (nil, num) = map (string.atoi, (m.groups ()[0:2]))
727                         entries = map (string.atoi, (m.groups ()[2:]))
728
729                         if self.tuplets[-1] == None or num <> self.tuplets[-1].start_note:
730                                 self.tuplets.append (Tuplet (num))
731
732                         self.tuplets[-1].append_finale (entries)
733                         
734         def try_IM (self, l):
735                 m = IMre.match (l)
736                 if m:
737                         a = string.atoi (m.group (1))
738                         b = string.atoi (m.group (2))
739
740                         fin = map (string.atoi, m.groups ()[2:])
741
742                         self.articulations.append (Articulation (a,b,fin))
743                 return m
744         def try_verse (self,l):
745                 m =  versere .match (l)
746                 if m:
747                         a = string.atoi (m.group (1))
748                         body =m.group (2)
749
750                         body = re.sub (r"""\^[a-z]+\([^)]+\)""", "", body)
751                         body = re.sub ("\^[a-z]+", "", body)
752                         self.verses.append (Verse (a, body))
753                         
754                 return m
755         def try_ve (self,l):
756                 m = vere .match (l)
757                 if m:
758                         a = string.atoi (m.group (1))
759                         b = string.atoi (m.group (2))
760
761                         fin = map (string.atoi, m.groups ()[2:])
762
763                         self.syllables.append (Syllable (a,b,fin))
764                 return m
765         def try_eE (self, l):
766                 m = eEre.match (l)
767                 if m:
768                         tup = m.groups()
769                         (no, prev, next, dur, pos, entryflag, extended, follow) = tup
770                         (no, prev, next, dur, pos,extended, follow) \
771                           = tuple (map (string.atoi, [no,prev,next,dur,pos,extended,follow]))
772
773                         entryflag = string.atol (entryflag,16)
774                         if len (self.entries) <= no:
775                                 # missing entries seem to be quite common.
776                                 # we fill'em up with None.
777                                 self.entries = self.entries + [None] * (no - len (self.entries) + 1)
778                                         
779                         current_entry = ((no, prev, next, dur, pos, entryflag, extended, follow), [])
780                         self.entries[no] = current_entry
781                 return m
782
783         def try_Sx(self,l):
784                 m = Sxre.match (l)
785                 if m:
786                         slurno = string.atoi (m.group (1))
787
788                         sl = None
789                         try:
790                                 sl = self.slur_dict[slurno]
791                         except KeyError:
792                                 sl = Slur (slurno)
793                                 self.slur_dict[slurno] = sl
794
795                         params = list (m.groups ()[1:])
796                         params = map (string.atoi, params)
797                         sl.append_entry (params)
798
799                 return m        
800         def try_GF(self, l):
801                 m = GFre.match (l)
802                 if m:
803                         (staffno,measno) = m.groups ()[0:2]
804                         s = string.atoi (staffno)
805                         me = string.atoi (measno)
806                         
807                         entry = m.groups () [2:]
808                         st = self.get_staff (s)
809                         meas = st.get_measure (me)
810                         meas.add_finale_entry (entry)
811                 
812         # frame  ?
813         def try_FR(self, l):
814                 m = FRre.match (l)
815                 if m:
816                         (frameno, startnote, endnote, foo, bar) = m.groups ()
817                         (frameno, startnote, endnote)  = tuple (map (string.atoi, [frameno, startnote, endnote]))
818                         if len (self.frames) <= frameno:
819                                 self.frames = self.frames + [None]  * (frameno - len(self.frames) + 1)
820                         
821                         self.frames[frameno] = Frame ((frameno, startnote, endnote))
822                         
823                 return m
824         
825         def try_MS (self, l):
826                 m = MSre.match (l)
827                 if m:
828                         measno = string.atoi (m.group (1))
829                         keynum = string.atoi (m.group (3))
830                         meas =self. get_global_measure (measno)
831                         meas.set_keysig (keynum)
832
833                         beats = string.atoi (m.group (4))
834                         beatlen = string.atoi (m.group (5))
835                         meas.set_timesig ((beats, beatlen))
836                                                 
837                 return m
838
839         def try_note (self, l):
840                 m = note_re.match (l)
841                 if m:
842                         (pitch, flag) = m.groups ()
843                         pitch = string.atoi (pitch)
844                         flag = string.atol (flag,16)
845                         self.entries[-1][1].append ((pitch,flag))
846
847         def parse (self, name):
848                 sys.stderr.write ('parsing ...')
849                 sys.stderr.flush ()
850
851                 gulp = open (name).read ()
852
853                 gulp = re.sub ('[\n\r]+', '\n',  gulp)
854                 ls = string.split (gulp, '\n')
855                 
856                 for l in ls:
857                         m = None
858                         if not m: 
859                                 m = self.try_MS (l)
860                         if not m: 
861                                 m = self.try_FR (l)
862                         if not m: 
863                                 m = self.try_GF (l)
864                         if not m: 
865                                 m = self.try_note (l)
866                         if not m: 
867                                 m = self.try_eE (l)
868                         if not m:
869                                 m = self.try_IM (l)
870                         if not m:
871                                 m = self.try_Sx (l)
872                         if not m:
873                                 m = self.try_TP (l)
874                         if not m:
875                                 m = self.try_verse (l)
876
877                 sys.stderr.write ('processing ...')
878                 sys.stderr.flush ()
879
880                 self.unthread_entries ()
881
882                 for st in self.staffs[1:]:
883                         if not st:
884                                 continue
885                         mno = 1
886                         for m in st.measures[1:]:
887                                 if not m:
888                                         continue
889                                 
890                                 m.calculate()
891                                 try:
892                                         m.global_measure = self.measures[mno]
893                                 except IndexError:
894                                         sys.stderr.write ("Non-existent global measure %d" % mno)
895                                         continue
896                                 
897                                 frame_obj_list = [None]
898                                 for frno in m.frames:
899                                         fr = self.frames[frno]
900                                         frame_obj_list.append (fr)
901
902                                 m.frames = frame_obj_list
903                                 for fr in frame_obj_list[1:]:
904                                         if not fr:
905                                                 continue
906                                         
907                                         fr.set_measure (m)
908                                         
909                                         fr.chords = self.get_thread (fr.start, fr.end)
910                                         for c in fr.chords:
911                                                 c.frame = fr
912                                 mno = mno + 1
913
914                 for c in self.chords[1:]:
915                         if c:
916                                 c.calculate()
917
918                 for f in self.frames[1:]:
919                         if f:
920                                 f.calculate ()
921                         
922                 for t in self.tuplets[1:]:
923                         t.calculate (self.chords)
924                         
925                 for s in self.slur_dict.values():
926                         s.calculate (self.chords)
927                 for s in self.articulations[1:]:
928                         s.calculate (self.chords)
929                         
930         def get_thread (self, startno, endno):
931
932                 thread = []
933
934                 c = None
935                 try:
936                         c = self.chords[startno]
937                 except IndexError:
938                         sys.stderr.write ("Huh? Frame has invalid bounds (%d,%d)\n" % (startno, endno))
939                         return []
940
941                 
942                 while c and c.number () <> endno:
943                         thread.append (c)
944                         c = c.next
945
946                 if c: 
947                         thread.append (c)
948                 
949                 return thread
950
951         def dump (self):
952                 str = ''
953                 staffs = []
954                 for s in self.staffs[1:]:
955                         if s:
956                                 str = str + '\n\n' + s.dump () 
957                                 staffs.append ('\\' + s.staffid ())
958
959
960                 # should use \addlyrics ?
961
962                 for v in self.verses[1:]:
963                         str = str + v.dump()
964
965                 if len (self.verses) > 1:
966                         sys.stderr.write ("\nLyrics found; edit to use \\addlyrics to couple to a staff\n")
967                         
968                 if staffs:
969                         str = str + '\\score { < %s > } ' % string.join (staffs)
970                         
971                 return str
972
973
974         def __str__ (self):
975                 return 'ETF FILE %s %s' % (self.measures,  self.entries)
976         
977         def unthread_entries (self):
978                 self.chords = [None]
979                 for e in self.entries[1:]:
980                         ch = None
981                         if e:           
982                                 ch = Chord (e)
983                         self.chords.append (ch)
984                                 
985                 for e in self.chords[1:]:
986                         if not e:
987                                 continue
988                         e.prev = self.chords[e.finale[0][1]]
989                         e.next = self.chords[e.finale[0][2]]
990
991 def identify():
992         sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
993
994 def help ():
995         print """Usage: etf2ly [OPTION]... ETF-FILE
996
997 Convert ETF to LilyPond.
998
999 Options:
1000   -h,--help          this help
1001   -o,--output=FILE   set output filename to FILE
1002   -v,--version       version information
1003
1004 Enigma Transport Format is a format used by Coda Music Technology's
1005 Finale product. This program will convert a subset of ETF to a
1006 ready-to-use lilypond file.
1007
1008 Report bugs to bug-gnu-music@gnu.org
1009
1010 Written by  Han-Wen Nienhuys <hanwen@cs.uu.nl>
1011 """
1012
1013 def print_version ():
1014         print r"""etf2ly (GNU lilypond) %s
1015
1016 This is free software.  It is covered by the GNU General Public License,
1017 and you are welcome to change it and/or distribute copies of it under
1018 certain conditions.  Invoke as `midi2ly --warranty' for more information.
1019
1020 Copyright (c) 2000 by Han-Wen Nienhuys <hanwen@cs.uu.nl>
1021 """ % version
1022
1023
1024
1025 (options, files) = getopt.getopt (sys.argv[1:], 'vo:h', ['help','version', 'output='])
1026 out_filename = None
1027
1028 for opt in options:
1029         o = opt[0]
1030         a = opt[1]
1031         if o== '--help' or o == '-h':
1032                 help ()
1033                 sys.exit (0)
1034         if o == '--version' or o == '-v':
1035                 print_version ()
1036                 sys.exit(0)
1037                 
1038         if o == '--output' or o == '-o':
1039                 out_filename = a
1040         else:
1041                 print o
1042                 raise getopt.error
1043
1044 identify()
1045
1046 for f in files:
1047         if f == '-':
1048                 f = ''
1049
1050         sys.stderr.write ('Processing `%s\'\n' % f)
1051         e = Etf_file(f)
1052         if not out_filename:
1053                 out_filename = os.path.basename (re.sub ('(?i).etf$', '.ly', f))
1054                 
1055         if out_filename == f:
1056                 out_filename = os.path.basename (f + '.ly')
1057                 
1058         sys.stderr.write ('Writing `%s\'' % out_filename)
1059         ly = e.dump()
1060
1061         
1062         
1063         fo = open (out_filename, 'w')
1064         fo.write ('%% lily was here -- automatically converted by etf2ly from %s\n' % f)
1065         fo.write(ly)
1066         fo.close ()
1067