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