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