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