]> git.donarmstrong.com Git - lilypond.git/blob - scripts/mudela-book.py
release: 1.2.3
[lilypond.git] / scripts / mudela-book.py
1 #!@PYTHON@
2
3 import os
4 import string
5 import re
6 import getopt
7 import sys
8 import __main__
9
10 outdir = 'out'
11 initfile = ''
12 program_version = '@TOPLEVEL_VERSION@'
13
14 cwd = os.getcwd ()
15 include_path = [cwd]
16
17 # TODO: use splitting iso. \mudelagraphic.
18
19 #
20 default_music_fontsize = 16
21 default_text_fontsize = 12
22
23 # latex linewidths:
24 # indices are no. of columns, papersize,  fontsize
25 # Why can't this be calculated?
26 latex_linewidths = {
27  1: {'a4':{10: 345, 11: 360, 12: 390},
28          'a5':{10: 276, 11: 276, 12: 276},
29          'b5':{10: 345, 11: 356, 12: 356},
30          'letter':{10: 345, 11: 360, 12: 390},
31          'legal': {10: 345, 11: 360, 12: 390},
32          'executive':{10: 345, 11: 360, 12: 379}},
33  2: {'a4':{10: 167, 11: 175, 12: 190},
34          'a5':{10: 133, 11: 133, 12: 133},
35          'b5':{10: 167, 11: 173, 12: 173},
36          'letter':{10: 167, 11: 175, 12: 190},
37          'legal':{10: 167, 11: 175, 12: 190},
38          'executive':{10: 167, 11: 175, 12: 184}}}
39
40
41 options = [
42   ('DIM',  '', 'default-mudela-fontsize', 'default fontsize for music.  DIM is assumed to in points'),
43   ('EXT', 'f', 'format', 'set format.  EXT is one of texi and latex.'),
44   ('', 'h', 'help', 'print help'),
45   ('DIR', 'I', 'include', 'include path'),
46   ('', '', 'init', 'mudela-book initfile'),
47 #  ('DIM', '', 'force-mudela-fontsize', 'force fontsize for all inline mudela. DIM is assumed to in points'),
48   ('', '', 'force-verbatim', 'make all mudela verbatim'),
49   ('', 'M', 'dependencies', 'write dependencies'),
50   ('', 'n', 'no-lily', 'don\'t run lilypond'),
51   ('FILE', 'o', 'outname', 'prefix for filenames'),
52   ('', 'v', 'version', 'print version information' )
53   ]
54
55 format = ''
56 run_lilypond = 1
57 no_match = 'a\ba'
58
59 # format specific strings, ie. regex-es for input, and % strings for output
60 output_dict= {
61         'latex': {
62                 'output-mudela-fragment' : r"""\begin[eps,fragment%s]{mudela}
63   \context Staff <
64     \context Voice{
65       %s
66     }
67   >
68 \end{mudela}""", 
69                 'output-mudela':r"""\begin%s{mudela}
70 %s
71 \end{mudela}""",
72                 'output-verbatim': r"""\begin{verbatim}%s\end{verbatim}""",
73                 'output-default-post': r"""\def\postMudelaExample{}""",
74                 'output-default-pre': r"""\def\preMudelaExample{}""",
75                 'output-eps': '\\noindent\\parbox{\\mudelaepswidth{%s.eps}}{\includegraphics{%s.eps}}',
76                 'output-tex': '\\preMudelaExample \\input %s.tex \\postMudelaExample\n'
77                 },
78         'texi' : {'output-mudela': """@mudela[%s]
79 %s
80 @end mudela
81 """,
82                   'output-verbatim': r"""@example
83 %s
84 @end example
85 """,
86                   'output-all': r"""@tex
87 \input %s.tex
88 @end tex
89 @html
90 <img src=%s.png>
91 @end html
92 """,
93                 }
94         }
95
96 re_dict = {
97         'latex': {'input': '\\\\input{?([^}\t \n}]*)',
98                   'include': '\\\\include{([^}]+)}',
99                  
100                   'comma-sep' : ', *',
101                   'header': r"""\\documentclass(\[.*?\])?""",
102                   'preamble-end': '\\\\begin{document}',
103                   'verbatim': r"""(?s)\\begin{verbatim}(.*?)\\end{verbatim}""",
104                   'verb': r"""\\verb(.)(.*?)\1""",
105                   'mudela-file': '\\\\mudelafile(\[[^\\]]+\])?{([^}]+)}',
106                   'mudela' : '\\\\mudela(\[.*?\])?{(.*?)}',
107                   'mudela-block': r"""(?s)\\begin(\[.*?\])?{mudela}(.*?)\\end{mudela}""",
108                   'interesting-cs': '\\\\(chapter|section|twocolumn|onecolumn)',
109                   'def-post-re': r"""\\def\\postMudelaExample""",
110                   'def-pre-re': r"""\\def\\preMudelaExample""",           
111                   },
112         'texi': {'input': '@include[ \n\t]+([^\t \n]*)',
113                  'include': no_match,
114                  'header': no_match,
115                  'preamble-end': no_match,
116                  'verbatim': r"""(?s)@example(.*?)@end example$""",
117                  'verb': r"""@code{(.*?)}""",
118                  'mudela-file': '@mudelafile(\[[^\\]]+\])?{([^}]+)}',
119                  'mudela' : '@mudela(\[.*?\])?{(.*?)}',
120                  'mudela-block': r"""(?s)@mudela(\[.*?\])?(.*?)@end mudela""",
121                  'interesting-cs': r"""[\\@](node|mudelagraphic)""",
122                   'comma-sep' : ', *',           
123                  }
124         }
125
126
127 for r in re_dict.keys ():
128         olddict = re_dict[r]
129         newdict = {}
130         for k in olddict.keys ():
131                 newdict[k] = re.compile (olddict[k])
132         re_dict[r] = newdict
133
134         
135 def get_output (name):
136         return  output_dict[format][name]
137
138 def get_re (name):
139         return  re_dict[format][name]
140
141
142 def bounding_box_dimensions(fname):
143         try:
144                 fd = open(fname)
145         except IOError:
146                 error ("Error opening `%s'" % fname)
147         str = fd.read (-1)
148         s = re.search('%%BoundingBox: ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)', str)
149         if s:
150                 return (int(s.group(3))-int(s.group(1)), 
151                         int(s.group(4))-int(s.group(2)))
152         else:
153                 return (0,0)
154
155
156 def find_file (name):
157         for a in include_path:
158                 try:
159                         nm = os.path.join (a, name)
160                         f = open (nm)
161                         return nm
162                 except IOError:
163                         pass
164         return ''
165
166 def error (str):
167         sys.stderr.write (str + "\n  Exiting ... \n\n")
168         raise 'Exiting.'
169
170
171 def compose_full_body (body, opts):
172         "Construct the text of an input file: add stuff to BODY using OPTS as options."
173         paper = 'a4'
174         music_size = default_music_fontsize
175         latex_size = default_text_fontsize
176
177         cols = 1
178         for o in opts:
179                 m = re.search ('^(.*)paper$', o)
180                 if m:
181                         paper = m.group (1)
182                 
183
184                 m = re.match ('([0-9]+)pt', o)
185                 if m:
186                         music_size = string.atoi(m.group (1))
187
188                 m = re.match ('latexfontsize=([0-9]+)pt', o)
189                 if m:
190                         latex_size = string.atoi (m.group (1))
191
192
193         if 'twocolumn' in opts:
194                 cols = 2
195                 
196         if 'fragment' or 'singleline' in opts:
197                 l = -1.0;
198         else:
199                 l = latex_linewidths[cols][paper][latex_size]
200
201         # urg: breaks on \include of full score
202         # Use nofly option if you want to \include full score.
203         if not 'nofly' in opts and not re.search ('\\\\score', body):
204                 opts.append ('fly')
205
206         if 'fly' in opts:
207                 body = r"""\score { 
208   \notes\relative c {
209     %s
210   }
211   \paper { }  
212 }""" % body
213
214                 
215         body = r"""
216 %% Generated by mudela-book.py
217 \include "paper%d.ly"
218 \paper  { linewidth = %f \pt; } 
219 """ % (music_size, l) + body
220
221         return body
222
223 def inclusion_func (match, surround):
224         insert = match.group (0)
225         try:
226                 (insert, d) = read_doc_file (match.group(1))
227                 deps = deps + d
228                 insert = surround + insert + surround
229         except:
230                 sys.stderr.write("warning: can't find %s, let's hope latex will\n" % m.group(1))
231
232         return (insert, deps)
233
234 def find_inclusion_chunks (regex, surround, str):
235         chunks = []
236         while str:
237                 m = regex.search (str)
238
239                 if m == None:
240                         chunks.append (('input', str))
241                         str = ''
242                         break
243
244                 chunks.append (('input', str[: m.start (0)]))
245                 chunks.append (('input', surround))
246                 chunks = chunks + read_doc_file (m.group (1))
247                 chunks.append (('input', surround))
248
249                 str = str [m.end (0):]
250         return chunks
251
252 def find_include_chunks (str):
253         return find_inclusion_chunks (get_re ('include'), '\\newpage', str)
254
255 def find_input_chunks (str):
256         return find_inclusion_chunks (get_re ('input'), '', str)        
257
258 def read_doc_file (filename):
259         """Read the input file, substituting for \input, \include, \mudela{} and \mudelafile"""
260         str = ''
261         for fn in [filename, filename+'.tex', filename+'.doc']:
262                 try:
263                         f = open(fn)
264                         str = f.read (-1)
265                 except:
266                         pass
267                 
268
269         if not str:
270                 raise IOError
271
272         retdeps =  [filename]
273
274         if __main__.format == '':
275                 latex =  re.search ('\\\\document', str[:200])
276                 texinfo =  re.search ('@node', str[:200])
277                 if (texinfo and latex) or not (texinfo or latex):
278                         error("error: can't determine format, please specify")
279                 if texinfo:
280                         __main__.format = 'texi'
281                 else:
282                         __main__.format = 'latex'
283                         
284         chunks = find_verbatim_chunks (str)
285         newchunks = []
286
287         for func in (find_include_chunks, find_input_chunks):
288                 for c in chunks:
289                         if c[0] == 'input':
290                                 ch = func (c[1])
291                                 newchunks = newchunks + ch
292                         else:
293                                 newchunks.append (c)
294
295         
296         return chunks
297
298
299
300 def scan_preamble (str):
301         options = []
302         m = get_re ('header').search( str)
303
304         # should extract paper & fontsz.
305         if m and m.group (1):
306                 options = options + re.split (',[\n \t]*', m.group(1)[1:-1])
307
308         def verbose_fontsize ( x):
309                 # o ??
310                 #if o.match('[0-9]+pt'):
311                 if re.match('[0-9]+pt', x):
312                         return 'latexfontsize=' + x
313                 else:
314                         return x 
315                         
316         options = map (verbose_fontsize, options)
317
318         return options
319
320
321 def completize_preamble (str):
322         m = get_re ('preamble-end').search( str)
323         if not m:
324                 return str
325         
326         preamble = str [:m.start (0)]
327         str = str [m.start(0):]
328         
329         if not get_re('def-post-re').search (preamble):
330                 preamble = preamble + get_output('output-default-post')
331         if not get_re ('def-pre-re').search(  preamble):
332                 preamble = preamble + get_output ('output-default-pre')
333
334         # UGH ! BUG!
335         #if  re.search ('\\\\includegraphics', str) and not re.search ('usepackage{graphics}',str):
336
337         preamble = preamble + '\\usepackage{graphics}\n'
338
339         return preamble + str
340
341 def find_verbatim_chunks (str):
342         """Chop STR into a list of tagged chunks, ie. tuples of form
343         (TYPE_STR, CONTENT_STR), where TYPE_STR is one of 'input' and 'verbatim'
344         """
345
346         
347         chunks = []
348         
349         while str:
350                 m = get_re ('verbatim').search( str)
351                 m2 = get_re ("verb").search( str)
352
353                 if  m == None and m2 == None:
354                         chunks.append (('input', str))
355                         str = ''
356                         break
357
358                 if m == None:
359                         m = m2
360
361                 if m2 and m2.start (0) < m.start (0):
362                         m = m2
363                         
364                 chunks.append (('input', str[:m.start (0)]))
365                 chunks.append (('verbatim', m.group (0)))
366                 
367                 str = str [m.end(0):]
368         return chunks         
369
370
371 def find_mudela_shorthand_chunks (str):
372         return [('input', find_mudela_shorthands(str))]
373         
374 def find_mudela_shorthands (b):
375         def mudela_short (match):
376                 "Find \mudela{}, and substitute appropriate \begin / \end blocks."
377                 opts = match.group (1)
378                 if opts:
379                         opts = ',' + opts[1:-1]
380                 else:
381                         opts = ''
382                 return get_output ('output-mudela-fragment')  % (opts, match.group (2))
383
384         def mudela_file (match):
385                 "Find \mudelafile, and substitute appropriate \begin / \end blocks."
386                 d = [] #, d = retdeps
387                 full_path = find_file (match.group (2))
388                 if not full_path:
389                         error("error: can't find file `%s'\n" % match.group(2))
390
391                 d.append (full_path)
392                 f = open (full_path)
393                 str = f.read (-1)
394                 opts = match.group (1)
395                 if opts:
396                         opts = re.split (',[ \n\t]*', opts[1:-1])
397                 else:
398                         opts = []
399
400                 if re.search ('.fly$', full_path):
401                         opts.append ('fly')
402                 elif re.search ('.sly$', full_path):
403                         opts = opts + [ 'fly','fragment']
404                 elif re.search ('.ly$', full_path):
405                         opts .append ('nofly')
406                         
407                 str_opts = string.join (opts, ',')
408                 if str_opts: str_opts = '[' + str_opts + ']'
409
410
411                 str = ("%% copied from file `%s'\n" % full_path) + str 
412                 return get_output ('output-mudela') % (str_opts, str)
413   
414         b = get_re('mudela-file').sub (mudela_file, b)
415         b = get_re('mudela').sub (mudela_short, b)
416         return b
417         
418 def find_mudela_chunks (str):
419         """Find mudela blocks, while watching for verbatim. Returns
420         (STR,MUDS) with \mudelagraphic substituted for the blocks in STR,
421         and the blocks themselves MUDS"""
422   
423         chunks = []
424         while str:
425                 m = get_re ("mudela-block").search( str)
426                 if not m:
427                         chunks.append (('input', str))
428                         str = ''
429                         break
430
431                 chunks.append (('input', str[:m.start (0)]))
432                 
433                 opts = m.group (1)
434                 if opts:
435                         opts = opts[1:-1]
436                 else:
437                         opts = ''
438                 optlist = get_re('comma-sep').split (opts)
439                 
440                 body = m.group (2)
441                 chunks.append (('mudela', body, optlist))
442   
443                 str = str [m.end (0):]
444   
445         return chunks
446   
447   
448   
449 def advance_counters (counter, opts, str):
450         """Advance chap/sect counters,
451         revise OPTS. Return the new counter tuple"""
452         
453         (chapter, section, count) = counter
454         done = ''
455         while str:
456                 m = get_re ('interesting-cs').search(str)
457                 if not m:
458                         done = done + str
459                         str = ''
460                         break
461                 
462                 done = done + str[:m.end (0)]
463                 str = str[m.end(0):]
464                 g = m.group (1)
465
466                 if g == 'twocolumn':
467                         opts.append ('twocolumn')
468                 elif g  == 'onecolumn':
469                         try:
470                                 current_opts.remove ('twocolumn')
471                         except IndexError:
472                                 pass
473                 elif g == 'chapter':
474                         (chapter, section, count)  = (chapter + 1, 0, 0)
475                 elif g == 'section' or g == 'node':
476                         (section, count)  = (section + 1, 0)
477                         
478
479         return (chapter, section, count)
480
481
482 def schedule_mudela_block (base, chunk, extra_opts):
483
484         """Take the body and options from CHUNK, figure out how the
485         real .ly should look, and what should be left MAIN_STR (meant
486         for the main file).  The .ly is written, and scheduled in
487         TODO.
488
489         Return: a chunk (TYPE_STR, MAIN_STR, OPTIONS, TODO)
490
491         TODO has format [basename, extension, extension, ... ]
492         
493         """
494
495         (type, body, opts) = chunk
496         assert type == 'mudela'
497         opts = opts +  extra_opts
498         
499         newbody = ''
500         if 'verbatim' in opts:
501                 verbatim_mangle = body
502                 if __main__.format == 'texi':
503                         verbatim_mangle = re.sub ('([{}])', '@\\1', body)
504                 newbody = get_output ('output-verbatim') % verbatim_mangle
505
506         file_body = compose_full_body (body, opts)
507         updated = update_file (file_body, base + '.ly')
508         todo = [base]                   # UGH.
509
510         if not os.path.isfile (base + '.tex') or updated:
511                 todo.append ('tex')
512                 updated = 1
513
514         for o in opts:
515                 m = re.search ('intertext="(.*?)"', o)
516                 if m:
517                         newbody = newbody  + m.group (1)
518
519         if format == 'texi':
520                 opts.append ('png')
521
522         if 'png' in opts:
523                 opts.append ('eps')
524
525         if 'eps' in opts and ('tex' in todo or
526                               not os.path.isfile (base + '.eps')):
527                 todo.append ('eps')
528
529         if 'png' in opts and ('eps' in todo or
530                               not os.path.isfile (base + '.png')):
531                 todo.append ('png')
532
533         if format == 'latex':
534                 if 'eps' in opts :
535                         newbody = newbody + get_output ('output-eps') %  (base, base)
536                 else:
537                         newbody = newbody + get_output ('output-tex') % base
538
539         elif format == 'texi':
540                 newbody = newbody + get_output ('output-all') % (base, base) 
541
542
543         
544         return ('mudela', newbody, opts, todo)
545
546 def find_eps_dims (match):
547         "Fill in dimensions of EPS files."
548         
549         fn =match.group (1)
550         dims = bounding_box_dimensions (fn)
551
552         return '%ipt' % dims[0]
553
554
555 def print_chunks (ch):
556         for c in ch:
557                 print '-->%s\n%s' % (c[0], c[1])
558                 if len (c) > 2:
559                         print '==>%s' % list (c[2:])
560         print foo
561
562
563 def transform_input_file (in_filename, out_filename):
564         """Read the input, and deliver a list of chunks
565         ready for writing.
566         """
567
568         chunks = read_doc_file (in_filename)
569
570         #.  Process \mudela and \mudelafile.
571         for func in [find_mudela_shorthand_chunks,
572                      find_mudela_chunks]:
573                 newchunks = []
574                 for c in chunks:
575                         if c[0] == 'input':
576                                 newchunks = newchunks + func (c[1])
577                         else:
578                                 newchunks.append (c)
579                 chunks = newchunks
580
581         opts = []
582         if chunks:
583                 opts = scan_preamble (chunks[0][1]) 
584         
585         (chap,sect,count) = (0,0,0)
586         newchunks = []
587         # Count sections/chapters.
588         for c in chunks:
589                 if c[0] == 'input':
590                         (chap,sect,count) = advance_counters((chap,sect,count), opts, c[1])
591                 elif c[0] == 'mudela':
592                         base = '%s-%d.%d.%d' % (out_filename, chap, sect, count)
593                         count = count + 1
594                         c = schedule_mudela_block (base, c, opts)
595                         
596                 newchunks.append (c)
597
598         chunks = newchunks
599         newchunks = []
600
601         # Do It.
602         if __main__.run_lilypond:
603                 compile_all_files (chunks)
604                 
605                 # finishing touch.
606                 for c in chunks:
607                         if c[0] == 'mudela' and 'eps' in c[2]:
608                                 body = re.sub (r"""\\mudelaepswidth{(.*?)}""", find_eps_dims, c[1])
609                                 newchunks.append (('mudela', body))
610                         else:
611                                 newchunks.append (c)
612
613
614         chunks = newchunks
615         if chunks and chunks[0][0] == 'input':
616                 chunks[0] = ('input', completize_preamble (chunks[0][1]))
617
618         return chunks
619
620 def system (cmd):
621         sys.stderr.write ("invoking `%s'\n" % cmd)
622         st = os.system (cmd)
623         if st:
624                 sys.stderr.write ('Error command exited with value %d\n' % st)
625         return st
626
627 def compile_all_files (chunks):
628         eps = []
629         tex = []
630         png = []
631
632         for c in chunks:
633                 if c[0] <> 'mudela':
634                         continue
635                 base  = c[3][0]
636                 exts = c[3][1:]
637                 for e in exts:
638                         if e == 'eps':
639                                 eps.append (base)
640                         elif e == 'tex':
641                                 tex.append (base + '.ly')
642                         elif e == 'png':
643                                 png.append (base)
644
645         if tex:
646                 lilyopts = map (lambda x:  '-I ' + x, include_path)
647                 lilyopts = string.join (lilyopts, ' ' )
648                 texfiles = string.join (tex, ' ')
649                 system ('lilypond %s %s' % (lilyopts, texfiles))
650
651         for e in eps:
652                 cmd = r"""tex %s; dvips -E -o %s %s""" % \
653                       (e, e + '.eps', e)
654                 system (cmd)
655
656         for g in png:
657                 cmd = r"""gs -sDEVICE=pgm  -dTextAlphaBits=4 -dGraphicsAlphaBits=4  -q -sOutputFile=- -r90 -dNOPAUSE %s -c quit | pnmcrop | pnmtopng > %s"""
658
659                 cmd = cmd % (g + '.eps', g + '.png')
660                 system (cmd)
661
662         
663 def update_file (body, name):
664         same = 0
665         try:
666                 f = open (name)
667                 fs = f.read (-1)
668                 same = (fs == body)
669         except:
670                 pass
671
672         if not same:
673                 f = open (name , 'w')
674                 f.write (body)
675                 f.close ()
676
677         
678         return not same
679
680
681
682 def getopt_args (opts):
683         "Construct arguments (LONG, SHORT) for getopt from  list of options."
684         short = ''
685         long = []
686         for o in opts:
687                 if o[1]:
688                         short = short + o[1]
689                         if o[0]:
690                                 short = short + ':'
691                 if o[2]:
692                         l = o[2]
693                         if o[0]:
694                                 l = l + '='
695                         long.append (l)
696         return (short, long)
697
698 def option_help_str (o):
699         "Transform one option description (4-tuple ) into neatly formatted string"
700         sh = '  '       
701         if o[1]:
702                 sh = '-%s' % o[1]
703
704         sep = ' '
705         if o[1] and o[2]:
706                 sep = ','
707                 
708         long = ''
709         if o[2]:
710                 long= '--%s' % o[2]
711
712         arg = ''
713         if o[0]:
714                 if o[2]:
715                         arg = '='
716                 arg = arg + o[0]
717         return '  ' + sh + sep + long + arg
718
719
720 def options_help_str (opts):
721         "Convert a list of options into a neatly formatted string"
722         w = 0
723         strs =[]
724         helps = []
725         for o in opts:
726                 s = option_help_str (o)
727                 strs.append ((s, o[3]))
728                 if len (s) > w:
729                         w = len (s)
730
731         str = ''
732         for s in strs:
733                 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0])  + 3), s[1])
734         return str
735
736 def help():
737         sys.stdout.write("""Usage: mudela-book [options] FILE\n
738 Generate hybrid LaTeX input from Latex + mudela
739 Options:
740 """)
741         sys.stdout.write (options_help_str (options))
742         sys.stdout.write (r"""Warning all output is written in the CURRENT directory
743
744
745
746 Report bugs to bug-gnu-music@gnu.org.
747
748 Written by Tom Cato Amundsen <tomcato@xoommail.com> and
749 Han-Wen Nienhuys <hanwen@cs.uu.nl>
750 """)
751
752         sys.exit (0)
753
754
755 def write_deps (fn, target,  deps):
756         sys.stdout.write('writing `%s\'\n' % fn)
757
758         f = open (fn, 'w')
759         
760         target = target + '.latex'
761         f.write ('%s: %s\n'% (target, string.join (deps, ' ')))
762         f.close ()
763
764                 
765 def identify():
766         sys.stdout.write ('mudela-book (GNU LilyPond) %s\n' % program_version)
767
768 def print_version ():
769         identify()
770         sys.stdout.write (r"""Copyright 1998--1999
771 Distributed under terms of the GNU General Public License. It comes with
772 NO WARRANTY.
773 """)
774
775
776 def main():
777         global outdir, initfile, defined_mudela_cmd, defined_mudela_cmd_re
778         outname = ''
779         try:
780                 (sh, long) = getopt_args (__main__.options)
781                 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
782         except getopt.error, msg:
783                 sys.stderr.write("error: %s" % msg)
784                 sys.exit(1)
785
786         do_deps = 0
787         for opt in options:     
788                 o = opt[0]
789                 a = opt[1]
790                 
791                 if o == '--include' or o == '-I':
792                         include_path.append (a)
793                 elif o == '--version':
794                         print_version ()
795                         sys.exit  (0)
796
797                 elif o == '--format' or o == '-o':
798                         __main__.format = a
799                 elif o == '--outname' or o == '-o':
800                         if len(files) > 1:
801                                 #HACK
802                                 sys.stderr.write("Mudela-book is confused by --outname on multiple files")
803                                 sys.exit(1)
804                         outname = a
805                 elif o == '--outdir' or o == '-d':
806                         outdir = a
807                 elif o == '--help' or o == '-h':
808                         help ()
809                 elif o == '--no-lily' or o == '-n':
810                         __main__.run_lilypond = 0
811                 elif o == '--dependencies':
812                         do_deps = 1
813                 elif o == '--default-mudela-fontsize':
814                         default_music_fontsize = string.atoi (a)
815                 elif o == '--init':
816                         initfile =  a
817         
818         identify()
819
820         for input_filename in files:
821                 file_settings = {}
822                 if outname:
823                         my_outname = outname
824                 else:
825                         my_outname = os.path.basename(os.path.splitext(input_filename)[0])
826                 my_depname = my_outname + '.dep'                
827
828                 chunks = transform_input_file (input_filename, my_outname)
829                 
830                 foutn = my_outname + '.' + format
831                 sys.stderr.write ("Writing `%s'\n" % foutn)
832                 fout = open (foutn, 'w')
833                 for c in chunks:
834                         fout.write (c[1])
835                 fout.close ()
836
837                 if do_deps:
838                         # write_deps (my_depname, my_outname, deps)
839                         sys.stderr.write ("--dependencies broken")
840
841 main()
842
843
844
845 #
846 # Petr, ik zou willen dat ik iets zinvoller deed,
847 # maar wat ik kan ik doen, het verandert toch niets?
848 #   --hwn 20/aug/99