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