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